Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

lc/1/ #2250

giscus[bot] bot announced in Announcements
lc/1/ #2250
Jan 23, 2024 · 7 comments · 4 replies
Discussion options

lc/1/

多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解

https://leetcode.doocs.org/lc/1/

You must be logged in to vote

Replies: 7 comments 4 replies

Comment options

yanglbme
Jan 23, 2024 — with giscus
Maintainer

最简单高效的解法,就是用哈希表

You must be logged in to vote
0 replies
Comment options

其他解法
解法一:对于每个元素nums[i],遍历右侧元素是否存在target-nums[i]。时间复杂度o(n^2)
解法二:先对数组排序,然后双指针分别指向数组开头和结尾,两元素相加,若和>target,则右指针左移,若和<target,则左指针右移,直至找到答案。时间复杂度取决于排序方法

You must be logged in to vote
1 reply
Comment options

yanglbme Feb 24, 2024 — with giscus
Maintainer

这两种解法可以的,不过复杂度高于哈希表的解法

Comment options

zhuhui 2024年06月04日 打卡

You must be logged in to vote
1 reply
Comment options

欢迎评论区打卡留言

Comment options

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 []
}
You must be logged in to vote
0 replies
Comment options

我直接return num1 + num2,然后你告诉我还能这么些

You must be logged in to vote
0 replies
Comment options

小白请教一下,在java的实现中为什么for的循环条件可以设置为空,这样不会导致无限循环吗

You must be logged in to vote
1 reply
Comment options

yanglbme May 14, 2025 — with giscus
Maintainer

因为题目保证一定存在一个有效答案。所以一定会 return,不会无限循环

Comment options

java有两种for循环。这里只讲和C语言格式一致的for循环。你只需要知道for循环代码块的执行顺序就可以了。确实可以设空。按顺序执行能退出就不是无限循环。 for(1;2;4){ 3 } 执行顺序是这样的。 另一种for循环,for(元素变量:集合){ ... } 我不是特别清楚,应该集合为空或者迭代到最后一个元素就可以退出了吧
...
---Original--- From: ***@***.***&gt; Date: Mon, May 12, 2025 22:39 PM To: ***@***.***&gt;; Cc: ***@***.******@***.***&gt;; Subject: Re: [doocs/leetcode] lc/1/ (Discussion #2250) 小白请教一下,在java的实现中为什么for的循环条件可以设置为空,这样不会导致无限循环吗 — Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you commented.Message ID: ***@***.***&gt;
You must be logged in to vote
1 reply
Comment options

yanglbme May 14, 2025 — with giscus
Maintainer

题目中,一定会 return,也就退出了循环。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

AltStyle によって変換されたページ (->オリジナル) /