diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index 0caf12be..4a8fa947 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -201,6 +201,54 @@ class Solution(object): ``` Go: +```go +func fourSum(nums []int, target int) [][]int { + if len(nums) < 4 { + return nil + } + sort.Ints(nums) + var res [][]int + for i := 0; i < len(nums)-3; i++ { + n1 := nums[i] + // if n1 > target { // 不能这样写,因为可能是负数 + // break + // } + if i > 0 && n1 == nums[i-1] { + continue + } + for j := i + 1; j < len(nums)-2; j++ { + n2 := nums[j] + if j > i+1 && n2 == nums[j-1] { + continue + } + l := j + 1 + r := len(nums) - 1 + for l < r { + n3 := nums[l] + n4 := nums[r] + sum := n1 + n2 + n3 + n4 + if sum < target { + l++ + } else if sum > target { + r-- + } else { + res = append(res, []int{n1, n2, n3, n4}) + for l < r && n3 == nums[l+1] { // 去重 + l++ + } + for l < r && n4 == nums[r-1] { // 去重 + r-- + } + // 找到答案时,双指针同时靠近 + r-- + l++ + } + } + } + } + return res +} +``` javaScript: diff --git a/problems/0100.相同的树.md b/problems/0100.相同的树.md index b536ffe3..c40f79fd 100644 --- a/problems/0100.相同的树.md +++ b/problems/0100.相同的树.md @@ -172,6 +172,22 @@ public: Java: +```java +class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p == null && q == null) { + return true; + } else if (q == null || p == null) { + return false; + } else if (q.val != p.val) { + return false; + } else { + return isSameTree(q.left, p.left) && isSameTree(q.right, p.right); + } + } +} + +``` Python: Go: diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index 875340c4..e3014d00 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -169,6 +169,46 @@ class Solution { } } ``` +javaScript +```js +var commonChars = function (words) { + let res = [] + let size = 26 + let firstHash = new Array(size) + for (let i = 0; i < size; i++) { // 初始化 hash 数组 + firstHash[i] = 0 + } + + let a = "a".charCodeAt() + let firstWord = words[0] + for (let i = 0; i < firstWord.length; i++) { // 第 0 个单词的统计 + let idx = firstWord[i].charCodeAt() + firstHash[idx - a] += 1 + } + + for (let i = 1; i < words.length; i++) { // 1-n 个单词统计 + let otherHash = new Array(size) + for (let i = 0; i < size; i++) { // 初始化 hash 数组 + otherHash[i] = 0 + } + + for (let j = 0; j < words[i].length; j++) { + let idx = words[i][j].charCodeAt() + otherHash[idx - a] += 1 + } + for (let i = 0; i < size; i++) { + firstHash[i] = Math.min(firstHash[i], otherHash[i]) + } + } + for (let i = 0; i < size; i++) { + while (firstHash[i] > 0) { + res.push(String.fromCharCode(i + a)) + firstHash[i]-- + } + } + return res +}; +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)