Three sum algorithm solution

后端 未结 4 1093
迷失自我
迷失自我 2020-12-16 23:53

Original Problem Statement:

Given an array S of n integers, are there elements a, b, C in S such that a + b + c = 0? Find all unique triplets in the array which gives

4条回答
  •  我在风中等你
    2020-12-17 00:27

    One of the approach is using the HashSet, What I have try here:

    public List> threeSum(int[] nums) {
            Set> set = new HashSet<>();
            Arrays.sort(nums);
            for (int i = 0; i < nums.length - 1; i++) {
                int j = i + 1;
                int k = nums.length - 1;
                while (j < k) {
                    int sum = nums[i] + nums[j] + nums[k];
                    if (sum == 0) {
                        set.add(Arrays.asList(nums[i], nums[j++], nums[k--]));
                    } else if (sum > 0) {
                        k--;
                    } else if (sum < 0) {
                        j++;
                    }
                }
            }
            return new ArrayList<>(set);
        }
    }
    

提交回复
热议问题