dengxinyi 6 роки тому
батько
коміт
97f5258657
2 змінених файлів з 94 додано та 0 видалено
  1. 60 0
      medium/385.mini-parser.go
  2. 34 0
      medium/386.lexicographical-numbers.go

+ 60 - 0
medium/385.mini-parser.go

@@ -0,0 +1,60 @@
+/**
+ * // This is the interface that allows for creating nested lists.
+ * // You should not implement it, or speculate about its implementation
+ * type NestedInteger struct {
+ * }
+ *
+ * // Return true if this NestedInteger holds a single integer, rather than a nested list.
+ * func (n NestedInteger) IsInteger() bool {}
+ *
+ * // Return the single integer that this NestedInteger holds, if it holds a single integer
+ * // The result is undefined if this NestedInteger holds a nested list
+ * // So before calling this method, you should have a check
+ * func (n NestedInteger) GetInteger() int {}
+ *
+ * // Set this NestedInteger to hold a single integer.
+ * func (n *NestedInteger) SetInteger(value int) {}
+ *
+ * // Set this NestedInteger to hold a nested list and adds a nested integer to it.
+ * func (n *NestedInteger) Add(elem NestedInteger) {}
+ *
+ * // Return the nested list that this NestedInteger holds, if it holds a nested list
+ * // The list length is zero if this NestedInteger holds a single integer
+ * // You can access NestedInteger's List element directly if you want to modify it
+ * func (n NestedInteger) GetList() []*NestedInteger {}
+ */
+func deserialize(s string) *NestedInteger {
+	ni := &NestedInteger{}
+	if s == "[]" {
+		return ni
+	}
+	n := len(s)
+	if s[0] != '[' {
+		i, _ := strconv.Atoi(s)
+		ni.SetInteger(i)
+		return ni
+	}
+	prev, comma := 1, nextComma(s, 1, n-1)
+	for comma != -1 {
+		ni.Add(*deserialize(s[prev:comma]))
+		prev = comma + 1
+		comma = nextComma(s, prev, n-1)
+	}
+	ni.Add(*deserialize(s[prev : n-1]))
+	return ni
+}
+
+func nextComma(s string, beg, end int) int {
+	for cnt, i := 0, beg; i < end; i++ {
+		if s[i] == '[' {
+			cnt++
+		} else if s[i] == ']' {
+			cnt--
+		}
+		if cnt == 0 && s[i] == ',' {
+			return i
+		}
+	}
+	return -1
+}
+

+ 34 - 0
medium/386.lexicographical-numbers.go

@@ -0,0 +1,34 @@
+func lexicalOrder(n int) []int {
+	res := make([]int, n)
+	if n == 0 {
+		return res
+	}
+	res[0] = 1
+	for i := 1; i < n; i++ {
+		if pre := res[i-1]; pre*10 <= n {
+			res[i] = pre * 10
+		} else if pre != n && pre%10 != 9 {
+			res[i] = pre + 1
+		} else {
+			for res[i] = pre / 10; res[i]%10 == 9; res[i] /= 10 {
+			}
+			res[i]++
+		}
+	}
+	return res
+}
+
+type ints []int
+
+func (is ints) Len() int           { return len(is) }
+func (is ints) Less(i, j int) bool { return strconv.Itoa(is[i]) < strconv.Itoa(is[j]) }
+func (is ints) Swap(i, j int)      { is[i], is[j] = is[j], is[i] }
+
+func lexicalOrderSort(n int) []int {
+	res := make([]int, n)
+	for i := 0; i < n; i++ {
+		res[i] = i + 1
+	}
+	sort.Sort(ints(res))
+	return res
+}