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

Commit 1bd8143

Browse files
authored
Update 0015.三数之和.md
增加了java语言版本的哈希解法
1 parent 586b8ef commit 1bd8143

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

‎problems/0015.三数之和.md‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ while (right > left) {
256256
## 其他语言版本
257257

258258
### Java:
259-
259+
(版本一) 双指针
260260
```Java
261261
class Solution {
262262
public List<List<Integer>> threeSum(int[] nums) {
@@ -297,7 +297,43 @@ class Solution {
297297
}
298298
}
299299
```
300+
(版本二) 使用哈希集合
301+
```Java
302+
class Solution {
303+
public List<List<Integer>> threeSum(int[] nums) {
304+
List<List<Integer>> result = new ArrayList<>();
305+
Arrays.sort(nums);
300306

307+
for (int i = 0; i < nums.length; i++) {
308+
// 如果第一个元素大于零,不可能凑成三元组
309+
if (nums[i] > 0) {
310+
return result;
311+
}
312+
// 三元组元素a去重
313+
if (i > 0 && nums[i] == nums[i - 1]) {
314+
continue;
315+
}
316+
317+
HashSet<Integer> set = new HashSet<>();
318+
for (int j = i + 1; j < nums.length; j++) {
319+
// 三元组元素b去重
320+
if (j > i + 2 && nums[j] == nums[j - 1] && nums[j - 1] == nums[j - 2]) {
321+
continue;
322+
}
323+
324+
int c = -nums[i] - nums[j];
325+
if (set.contains(c)) {
326+
result.add(Arrays.asList(nums[i], nums[j], c));
327+
set.remove(c); // 三元组元素c去重
328+
} else {
329+
set.add(nums[j]);
330+
}
331+
}
332+
}
333+
return result;
334+
}
335+
}
336+
```
301337
### Python:
302338
(版本一) 双指针
303339

0 commit comments

Comments
(0)

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