LeetCode 15. 三数之和 java实现
下面的代码在本地的用例中可以实现,可是提交的时候有用例过不了,希望有大神帮我解答一下这种利用map或者set来减少时间复杂度的解法。
题目:
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
解题思路:
1,遍历两次,一次遍历a,第二次遍历b
2,第三次使用map来保存整个数组,第三个数(c=0 - a - b;)从map数组中找出
代码如下:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
if(nums.length < 3)
return null;
List<List<Integer>> listOut=new ArrayList<>();//返回的list集合
HashMap<Integer, Integer> map = new HashMap<>();
Set set = new HashSet();//去掉重复的set
int[] result = new int[3];
Arrays.sort(nums);//先对数组nums排序
for(int i=0;i<nums.length - 2;i++){//遍历a
for(int j=i+1;j<nums.length;j++){//遍历b
int a = nums[i];
int b= nums[j];
int c = 0 - a - b;//得到c
if(map.containsKey(nums[j])){//如过map里面包含当前的c
List<Integer> tempList = new ArrayList<>();
int x = nums[i];//获得第一个数
int y = nums[map.get(nums[j])];//
tempList.add(x);
tempList.add(y);
tempList.add(nums[j]);
set.add(tempList);
}
map.put(c,j);
}
map.clear();
}
listOut = new ArrayList<>(set);//set转换成list
return listOut;
}
}