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

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

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

 

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

Note:The solution set must not contain duplicate triplets.

 

public List> threeSum(int[] nums) {
        Arrays.sort(nums);
        ArrayList> result = new ArrayList<>();
        HashSet> hashSet = new HashSet<>();

        for (int i = 0; i < nums.length - 2; i++) {
            if (nums[i] >  0) break;

            int low = i + 1;
            int high = nums.length - 1;

            while (low < high) {
                if (nums[low] + nums[high] + nums[i] == 0) {
                    if (!hashSet.contains(Arrays.asList(nums[i], nums[low], nums[high]))) {
                        hashSet.add(Arrays.asList(nums[i], nums[low], nums[high]));
                        result.add(Arrays.asList(nums[i], nums[low], nums[high]));
                    }

                    while (low < high && nums[low] == nums[low + 1]) low++;
                    while (low < high && nums[high] == nums[high - 1]) high--;

                    low++;
                    high--;
                } else if (nums[low] + nums[high] + nums[i] > 0 ) {
                    high--;
                } else {
                    low++;
                }

            }
        }

        return result;
    }

 

你可能感兴趣的:(leetcode)