funcconstructMaximumBinaryTree(nums []int) *TreeNode { iflen(nums) == 0 { returnnil } best := 0 for i, num := range nums { if num > nums[best] { best = i } } return &TreeNode{nums[best], constructMaximumBinaryTree(nums[:best]), constructMaximumBinaryTree(nums[best+1:])} }
funcisPrefixOfWord(sentence string, searchWord string)int { ans := -1 wordnow := 1 right := true for j := 0; j < len(searchWord); j++ { if j < len(sentence) && searchWord[j] != sentence[j] { right = false } } if right == true { ans = wordnow return ans } for i := 0; i < len(sentence); i++ { if sentence[i] == ' ' { wordnow++ right = true for j := 0; j < len(searchWord); j++ { if i+j+1 < len(sentence) && searchWord[j] != sentence[i+j+1] { right = false } } if right == true { ans = wordnow return ans } } } return ans }
funcprintTree(root *TreeNode) [][]string { height := depth(root) - 1 m := height + 1 n := 1<<(height+1) - 1 ans := make([][]string, m) for i := 0; i < m; i++ { ans[i] = make([]string, n) } var f func(root *TreeNode, r int, c int) f = func(root *TreeNode, r int, c int) { if root == nil { return } ans[r][c] = strconv.Itoa(root.Val) if root.Left != nil { f(root.Left, r+1, c-(1<<(height-r-1))) } if root.Right != nil { f(root.Right, r+1, c+(1<<(height-r-1))) } } f(root, 0, (n-1)/2) return ans }
funcabs(x int)int { if x < 0 { return -x } return x }
funcmin(a, b int)int { if a > b { return b } return a }
review
掩码的写法很不错,自己位运算用的还是少太多了。
220824
daily-1460.通过翻转子数组使两个数组相等(algorithms Easy)
分析
不要求求最短,一张hashmap写完。
代码块
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funccanBeEqual(target []int, arr []int)bool { hashmap := make(map[int]int) for i := 0; i < len(target); i++ { hashmap[target[i]]++ hashmap[arr[i]]-- } for key, _ := range hashmap { if hashmap[key] != 0 { returnfalse } } returntrue }
review
偏水。
220825
daily-658.找到-k-个最接近的元素(algorithms Medium)
分析
题给的数组排好序了,直接跟着条件搜就行。
代码块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcfindClosestElements(arr []int, k int, x int) []int { ans := make([]int, k) ans = arr[:k] for now := k; now < len(arr); now++ { if abs(arr[now]-x) < abs(ans[0]-x) { ans = arr[now+1-k : now+1] } } return ans }
funcabs(x int)int { if x < 0 { return -x } return x }
review
因为数据规模不大直接o(n)了,实际上用二分可以更快的。
220826
daily-1464.数组中两元素的最大乘积(algorithms Easy)
分析
找一个数组的最大值和次大值,你好水啊。
代码块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcmaxProduct(nums []int)int { max1 := 0 max2 := 1//larger if nums[0] > nums[1] { max2 = 0 max1 = 1 } for i := 2; i < len(nums); i++ { if nums[i] > nums[max2] { max1 = max2 max2 = i } elseif nums[i] > nums[max1] { max1 = i } } return (nums[max1] - 1) * (nums[max2] - 1) }