邓心一 6 anni fa
parent
commit
4810c7b8ef

+ 22 - 2
easy/437.path-sum-iii.go

@@ -6,6 +6,26 @@
  *     Right *TreeNode
  * }
  */
-func pathSum(root *TreeNode, sum int) int {
-    
+func pathSum(root *TreeNode, sum int) (cnt int) {
+	helper(root, []*TreeNode{}, sum, 0, &cnt)
+	return
+}
+
+func helper(node *TreeNode, path []*TreeNode, sum, currSum int, cnt *int) {
+	if node == nil {
+		return
+	}
+	currSum += node.Val
+	if currSum == sum {
+		(*cnt)++
+	}
+	n := len(path)
+	for cs, i := currSum, 0; i < n; i++ {
+		cs -= path[i].Val
+		if cs == sum {
+			(*cnt)++
+		}
+	}
+	helper(node.Left, append(path, node), sum, currSum, cnt)
+	helper(node.Right, append(path, node), sum, currSum, cnt)
 }

+ 24 - 0
easy/438.find-all-anagrams-in-a-string.go

@@ -0,0 +1,24 @@
+func findAnagrams(s string, p string) (res []int) {
+	freq, curr := make([]int, 256), make([]int, 256)
+	for _, r := range p {
+		freq[r]++
+	}
+	m, n := len(s), len(p)
+	ss := []rune(s)
+	for i := 0; i < m; i++ {
+		curr[ss[i]]++
+		if n-1 <= i {
+			same := true
+			for j := 'a'; j <= 'z'; j++ {
+				if freq[j] != curr[j] {
+					same = false
+				}
+			}
+			if same {
+				res = append(res, i-n+1)
+			}
+			curr[ss[i-n+1]]--
+		}
+	}
+	return
+}

+ 7 - 0
easy/441.arranging-coins.go

@@ -0,0 +1,7 @@
+func arrangeCoins(n int) int {
+	// (1 + x) * x <= 2 * n < (2 + x) * (1 + x)
+	lv := int(math.Sqrt(float64(2 * n)))
+	for target := 2 * n; target < lv*(lv+1); lv-- {
+	}
+	return lv
+}

+ 30 - 0
easy/443.string-compression.go

@@ -0,0 +1,30 @@
+func compress(chars []byte) int {
+	fast, slow, cnt, n := 1, 0, 1, len(chars)
+	if n <= 1 {
+		return n
+	}
+	for ; fast < n; fast++ {
+		if chars[fast] != chars[fast-1] {
+			chars[slow] = chars[fast-1]
+			slow++
+			if cnt != 1 {
+				num := strconv.Itoa(cnt)
+				for end, i := slow+len(num), 0; slow < end; slow, i = slow+1, i+1 {
+					chars[slow] = num[i]
+				}
+				cnt = 1
+			}
+		} else {
+			cnt++
+		}
+	}
+	chars[slow] = chars[fast-1]
+	slow++
+	if cnt != 1 {
+		num := strconv.Itoa(cnt)
+		for end, i := slow+len(num), 0; slow < end; slow, i = slow+1, i+1 {
+			chars[slow] = num[i]
+		}
+	}
+	return slow
+}

+ 3 - 0
easy/447.number-of-boomerangs.go

@@ -0,0 +1,3 @@
+func numberOfBoomerangs(points [][]int) int {
+    
+}