My long JAVA code


  • 0
    F
    public List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;
        List<List<Integer>> lists = new ArrayList<>();
        if (n < 3) {
            return lists;
        }
        Arrays.sort(nums);
        int i = 0;
        while (i <= n - 3) {
            int j = i + 1;
            int k = n - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                if (sum == 0) {
                    lists.add(Arrays.asList(nums[i], nums[j++], nums[k--]));
                    while (j < k && nums[j] == nums[j - 1])
                        j++;
                    while (j < k && nums[k] == nums[k + 1])
                        k--;
                }
                if (sum < 0) {
                    j++;
                    while (j < k && nums[j] == nums[j - 1])
                        j++;
                }
                if (sum > 0) {
                    k--;
                    while (j < k && nums[k] == nums[k + 1])
                        k--;
                }
            }
            i++;
            while (i <= n - 3 && nums[i] == nums[i - 1])
                i++;
        }
        return lists;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.