mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-12 05:20:59 +08:00
Update 0015.三数之和.md
增加了java语言版本的哈希解法
This commit is contained in:
@ -256,7 +256,7 @@ while (right > left) {
|
|||||||
## 其他语言版本
|
## 其他语言版本
|
||||||
|
|
||||||
### Java:
|
### Java:
|
||||||
|
(版本一) 双指针
|
||||||
```Java
|
```Java
|
||||||
class Solution {
|
class Solution {
|
||||||
public List<List<Integer>> threeSum(int[] nums) {
|
public List<List<Integer>> threeSum(int[] nums) {
|
||||||
@ -297,7 +297,43 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
(版本二) 使用哈希集合
|
||||||
|
```Java
|
||||||
|
class Solution {
|
||||||
|
public List<List<Integer>> threeSum(int[] nums) {
|
||||||
|
List<List<Integer>> result = new ArrayList<>();
|
||||||
|
Arrays.sort(nums);
|
||||||
|
|
||||||
|
for (int i = 0; i < nums.length; i++) {
|
||||||
|
// 如果第一个元素大于零,不可能凑成三元组
|
||||||
|
if (nums[i] > 0) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
// 三元组元素a去重
|
||||||
|
if (i > 0 && nums[i] == nums[i - 1]) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
HashSet<Integer> set = new HashSet<>();
|
||||||
|
for (int j = i + 1; j < nums.length; j++) {
|
||||||
|
// 三元组元素b去重
|
||||||
|
if (j > i + 2 && nums[j] == nums[j - 1] && nums[j - 1] == nums[j - 2]) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
int c = -nums[i] - nums[j];
|
||||||
|
if (set.contains(c)) {
|
||||||
|
result.add(Arrays.asList(nums[i], nums[j], c));
|
||||||
|
set.remove(c); // 三元组元素c去重
|
||||||
|
} else {
|
||||||
|
set.add(nums[j]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
### Python:
|
### Python:
|
||||||
(版本一) 双指针
|
(版本一) 双指针
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user