15. 3Sum (Medium)

https://leetcode.com/problems/3sum/

Given an array nums of n integers, are there elements a, b, c 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Hints

Solutions

  • Java
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums.length < 3) return result;

        Arrays.sort(nums);

        int l = nums.length;
        for (int i = 0; i < l - 2; i++) {
            // nums[i - 1] already calculated, skip nums[i] when of same value
            if (i != 0 && nums[i] == nums[i - 1]) continue; // optimization

            int j = i + 1, k = l - 1;
            while (k > j) {
                if (j != i + 1 && nums[j] == nums[j - 1]) { // optimization
                    j++;
                    continue;
                }

                if (k != l - 1 && nums[k] == nums[k + 1]) { // optimization
                    k--;
                    continue;
                }

                int sum = nums[i] + nums[j] + nums[k];
                if (sum > 0) k--;
                if (sum < 0) j++;
                if (sum == 0) {
                    result.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    k--;
                    j++;
                }
            }
        }

        return result;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-04 02:48:18

results matching ""

    No results matching ""