algorithm-base/animation-simulation/求和问题/三数之和.md

170 lines
7.7 KiB
Java
Raw Normal View History

2021-03-20 08:44:27 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [15. ](https://leetcode-cn.com/problems/3sum/)
2021-03-19 07:26:58 +00:00
##
> n nums nums abc 使 a + b + c = 0
>
>
> nums = [-1, 0, 1, 2, -1, -4]
>
>
> [
> [-1, 0, 1],
> [-1, -1, 2]
> ]
0 ()
###
####
[-2 , 1 , 1],[-2 , 1 , 1][1 , 1, -2] -21 1 1 1 -2
![640](https://cdn.jsdelivr.net/gh/tan45du/tan45du.github.io.photo@master/photo/640.9tp5a5guhr0.png)
-2 0 2
####
```java
class Solution {
public List<List<Integer>> threeSum (int[] nums) {
if (nums.length < 3) {
return new ArrayList<>();
}
//排序
Arrays.sort(nums);
HashMap<Integer,Integer> map = new HashMap<>();
List<List<Integer>> resultarr = new ArrayList<>();
//存入哈希表
for (int i = 0; i < nums.length; i++) {
map.put(nums[i],i);
}
Integer t;
int target = 0;
for (int i = 0; i < nums.length; ++i) {
target = -nums[i];
//去重
if (i > 0 && nums[i] == nums[i-1]) {
continue;
}
for (int j = i + 1; j < nums.length; ++j) {
if (j > i+1 && nums[j] == nums[j-1]) {
continue;
}
if ((t = map.get(target - nums[j])) != null) {
//符合要求的情况,存入
if (t > j) {
resultarr.add(new ArrayList<>
(Arrays.asList(nums[i], nums[j], nums[t])));
}
else {
break;
}
}
}
}
return resultarr;
}
}
```
###
####
Arrays.sort()
![](https://cdn.jsdelivr.net/gh/tan45du/tan45du.github.io.photo@master/photo/三数之和起始.44vete07oy80.png)
-3 0
-3 < 0
0 0 0 绿
![](https://cdn.jsdelivr.net/gh/tan45du/tan45du.github.io.photo@master/photo/三数之和举例.69b6nvlu4zc0.png)
0 - 1 + 1 = 0 0 -1 + 1 = 0
HashSet
使 while 0
0
![](https://cdn.jsdelivr.net/gh/tan45du/tan45du.github.io.photo@master/photo/三数之和例子.6c8xobhrieg0.png)
****
![](https://cdn.jsdelivr.net/gh/tan45du/tan45du.github.io.photo@master/photo/三数之和.5akhtx5y0g00.gif)
####
```java
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> arr = new ArrayList<List<Integer>>();
if(nums.length < 3){
return arr;
}
//排序
Arrays.sort(nums);
if(nums[0] > 0){
return arr;
}
for(int i = 0; i < nums.length-2; i++){
int target = 0 - nums[i];
//去重
if(i > 0 && nums[i] == nums[i-1]){
continue;
}
int l = i+1;
int r = nums.length - 1;
while(l < r){
if(nums[l] + nums[r] == target){
//存入符合要求的值
arr.add(new ArrayList<>(Arrays.asList(nums[i], nums[l], nums[r])));
//这里需要注意顺序
while(l < r && nums[l] == nums[l+1]) l++;
while(l < r && nums[r] == nums[r-1]) r--;
l++;
r--;
}
else if(nums[l] + nums[r] > target){
r--;
}
else{
l++;
}
}
}
return arr;
}
}
```