力扣(LeetCode)15. 三数之和

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

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

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

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

思路 用HashSet无重复的特点去重。

先将数组排序。 Arrays.sort(nums); //从小到大
用三个指针,i指向第一个元素,j指向第二个元素,k指向第三个元素。

java版

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        HashSet<List<Integer>> hashset = new HashSet<>();
 
        int i,j,k,len = nums.length;
        for(i=0;i<len-2;i++) {
            j = i+1;
            k = len-1;
            while(j < k) {
                int sum = nums[i]+nums[j]+nums[k];
                if(sum < 0) {
                    j++;
                }else if(sum > 0) {
                    k--;
                }else {
                    List<Integer> list1 = new ArrayList<>();
                    list1.add(nums[i]);
                    list1.add(nums[j]);
                    list1.add(nums[k]);
                    hashset.add(list1);
                   
                    j++;
                    k--;
                }
            }
        }
        if(hashset.size()!=0) {
            Iterator<List<Integer>> iterator = hashset.iterator();
            while(iterator.hasNext()) {
                list.add(iterator.next());
            }
        }
        return list;
    }
}

运行结果

猜你喜欢

转载自www.cnblogs.com/lick468/p/10658788.html
今日推荐