【力扣算法】15-三数之和

题目

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

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

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

题解

无官方题解

自己一开始双指针设计的不正确,编成两边a、c是指针,中间b遍历的方式,发现思路不正确。因为a右移和c左移的情况无法合并,所以得写成递归浪费时间。

后来参考评论区来源,编出来了:

执行用时 : 73 ms, 在3Sum的Java提交中击败了85.32% 的用户

内存消耗 : 57.3 MB, 在3Sum的Java提交中击败了56.18% 的用户

import java.util.*;
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ls = new ArrayList<>();
        if(nums.length<3) return ls;
        Arrays.sort(nums);
        for(int a=0;a<nums.length-2;a++){
        	if(a==0||nums[a]>nums[a-1]){
        		int b=a+1;
        		int c=nums.length-1;
        		while(c>b){
        			int sum=nums[a]+nums[b]+nums[c];
        			if(sum==0){
        				ls.add(Arrays.asList(nums[a], nums[b], nums[c]));
        				b++;
        				c--;
    	    			while (b<c && nums[b]==nums[b-1])b++;
        				while (b<c && nums[c]==nums[c+1])c--;//防止重复
        			}
        			else if(sum>0){
        				c--;
    	    		}
        			else{
        				b++;
        			}
        		}
       		}
        }
        
        return ls;	
    }
}

感想

有必要好好了解一下双指针方法了。

猜你喜欢

转载自blog.csdn.net/ZeromaXHe/article/details/89424298
今日推荐