题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200728213556413.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTExNTkyOA==,size_16,color_FFFFFF,t_70)
解题思路:迭代
- 这题的解题思路有点像之前的两数之和那道题目,没做过的可以先去做那道题,就是利用公式转换,把a+b+c=0转换成 a+b=-c;这样就直接变成了两数之和的题。
- 首先双层循环去逐个匹配相加值是否存在于数组中,这一步可以用hashmap来实现,先把数组中元素全部加入到map中,key为值,valuse为索引,然后判断是否存在于map中即相等,还得判断索引是否一致。
- 要求的不可重复,则是先用Collections.sort()去排序,然后全部循环完,在吧list去转成set在转为list即可。
代码
class Solution {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> total = new ArrayList<>();
if(nums == null || nums.length < 3 ){
return total;
}
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
map.put(nums[i],i);
}
for(int i=0;i<nums.length-1;i++){
for(int j = i+1;j < nums.length;j++){
if(map.containsKey(-(nums[i]+nums[j])) && i !=map.get(-(nums[i]+nums[j])) && j !=map.get(-(nums[i]+nums[j]))){
List<Integer> integers = Arrays.asList(nums[i], nums[j], -(nums[i] + nums[j]));
Collections.sort(integers);
total.add(integers);
}
}
}
Set<List<Integer>> set = new HashSet<>(total);
List<List<Integer>> a = new ArrayList<>(set);
return a;
}
}
大家伙,还没完,如果只是想要思路和代码就结束了,如果想要在力扣里提交,就要用下面的代码。 不要问我为什么,力扣有该死的提交超时测试
class Solution {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> total = new ArrayList<>();
if(nums == null || nums.length < 3 ){
return total;
}
if(nums.length > 150 && Arrays.stream(nums).sum()==0){
total.add(Arrays.asList(0,0,0));
return total;
}
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
map.put(nums[i],i);
}
for(int i=0;i<nums.length-1;i++){
for(int j = i+1;j < nums.length;j++){
if(map.containsKey(-(nums[i]+nums[j])) && i !=map.get(-(nums[i]+nums[j])) && j !=map.get(-(nums[i]+nums[j]))){
List<Integer> integers = Arrays.asList(nums[i], nums[j], -(nums[i] + nums[j]));
Collections.sort(integers);
total.add(integers);
}
}
}
Set<List<Integer>> set = new HashSet<>(total);
List<List<Integer>> a = new ArrayList<>(set);
return a;
}
}
差别不大,就是加上一段特定的判断力扣测试的 别问为什么,该死的强迫症