dengxinyi 6 năm trước cách đây
mục cha
commit
8bb8e46c62

+ 14 - 0
easy/566.reshape-the-matrix.go

@@ -0,0 +1,14 @@
+func matrixReshape(nums [][]int, r int, c int) [][]int {
+	m, n := len(nums), len(nums[0])
+	if m*n != r*c || (m == r && n == c) {
+		return nums
+	}
+	res := make([][]int, r)
+	for i := range res {
+		res[i] = make([]int, c)
+	}
+	for i := 0; i < r*c; i++ {
+		res[i/c][i%c] = nums[i/n][i%n]
+	}
+	return res
+}

+ 31 - 0
easy/572.subtree-of-another-tree.go

@@ -0,0 +1,31 @@
+/**
+ * Definition for a binary tree node.
+ * type TreeNode struct {
+ *     Val int
+ *     Left *TreeNode
+ *     Right *TreeNode
+ * }
+ */
+func isSubtree(s *TreeNode, t *TreeNode) bool {
+	return postorder(s, t)
+}
+
+func postorder(s *TreeNode, t *TreeNode) bool {
+	if s == nil {
+		return s == t
+	}
+	if postorder(s.Left, t) || postorder(s.Right, t) {
+		return true
+	}
+	return isSametree(s, t)
+}
+
+func isSametree(s *TreeNode, t *TreeNode) bool {
+	if s == nil || t == nil {
+		return s == t
+	}
+	if s.Val != t.Val {
+		return false
+	}
+	return isSametree(s.Left, t.Left) && isSametree(s.Right, t.Right)
+}

+ 13 - 0
easy/575.distribute-candies.go

@@ -0,0 +1,13 @@
+type none struct{}
+
+func distributeCandies(candies []int) int {
+	set := make(map[int]none)
+	for _, c := range candies {
+		set[c] = none{}
+	}
+	if half, kind := len(candies)/2, len(set); kind <= half {
+		return kind
+	} else {
+		return half
+	}
+}

+ 15 - 0
easy/581.shortest-unsorted-continuous-subarray.go

@@ -0,0 +1,15 @@
+func findUnsortedSubarray(nums []int) int {
+	n := len(nums)
+	sorted := make([]int, n)
+	copy(sorted, nums)
+	sort.Ints(sorted)
+	l, r := 0, n-1
+	for ; l < n && nums[l] == sorted[l]; l++ {
+	}
+	if l == n {
+		return 0
+	}
+	for ; nums[r] == sorted[r]; r-- {
+	}
+	return r - l + 1
+}