LeetCode 15 三数之和

148 阅读1分钟

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。 示例 1:

输入: nums = [-1,0,1,2,-1,-4]
输出: [[-1,-1,2],[-1,0,1]]

分析:一开始特别傻的用了三层for循环,最后一提交果不其然超时了。最后看了官方的解答,用了双指针,其实我觉得是三指针了。 1.首先对数组进行排序,然后对数组遍历,如果第i个元素就大于0,直接就跳出循环,应该后面其他加起来都是大于0了,不会等于0. 2. 设左指针L为i+1,右指针为数组长度-1 3. 如果nums[i]+nums[L]+nums[R]=0, 那么l++,R--。 如果相加小于0,则说明L小了,L++ 如果相加大于0,R--

public static List<List<Integer>> threeSums(int[] nums){
   Arrays.sort(nums);
   List<List<Integer>> res = new ArrayList<>();
   if (nums==null || nums.length<3){
       return res;
   }
   for (int i = 0; i < nums.length; i++) {
       int l = i+1;
       int R = nums.length-1;
       if (nums[i]>0){
           break;
       }
       if (i>0 && nums[i]==nums[i-1]) continue;
       while (l < R) {
           int sum = nums[i] + nums[l] + nums[R];
           if (sum == 0) {
               res.add(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 (sum<0) l++;
           else if (sum>0) R--;
       }
   }
   return res;
}

注意题目中说明到答案不能有重复解,所以要进行去重。即要判断每次遍历的nums[i]和前一个nums[i-1]是否相同,相同的话求出来的解也相同,则跳出此次循环,对于左指针和右指针的去重也是类似的。