-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
lc/1/ #2250
-
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 9 -
❤️ 1 -
🚀 1
Replies: 7 comments 4 replies
-
最简单高效的解法,就是用哈希表
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 5 -
🚀 1
-
其他解法
解法一:对于每个元素nums[i],遍历右侧元素是否存在target-nums[i]。时间复杂度o(n^2)
解法二:先对数组排序,然后双指针分别指向数组开头和结尾,两元素相加,若和>target,则右指针左移,若和<target,则左指针右移,直至找到答案。时间复杂度取决于排序方法
Beta Was this translation helpful? Give feedback.
All reactions
-
❤️ 4
-
这两种解法可以的,不过复杂度高于哈希表的解法
Beta Was this translation helpful? Give feedback.
All reactions
-
zhuhui 2024年06月04日 打卡
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 1
-
欢迎评论区打卡留言
Beta Was this translation helpful? Give feedback.
All reactions
-
Additionally to hash-table you can use approach with 2 pointers.
Formally time complexity will be the same O(n), but technically it should be 2 times faster.
But unfortunately it also comes with code duplication.. 🤷🏻
function twoSum(nums: number[], target: number): number[] { const map: Record<number, number> = {} const n = nums.length for (let l = 0, r = n - 1; l <= r; l++, r--) { let v = nums[l] let diff = target - v if (map[diff] !== undefined) return [map[diff], l] map[v] = l v = nums[r] diff = target - v if (map[diff] !== undefined) return [map[diff], r] map[v] = r } return [] }
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 2
-
我直接return num1 + num2,然后你告诉我还能这么些
Beta Was this translation helpful? Give feedback.
All reactions
-
😄 2 -
👀 1
-
小白请教一下,在java的实现中为什么for的循环条件可以设置为空,这样不会导致无限循环吗
Beta Was this translation helpful? Give feedback.
All reactions
-
因为题目保证一定存在一个有效答案。所以一定会 return,不会无限循环
Beta Was this translation helpful? Give feedback.
All reactions
-
Beta Was this translation helpful? Give feedback.
All reactions
-
题目中,一定会 return,也就退出了循环。
Beta Was this translation helpful? Give feedback.