Can anyone tell me why my solution is wrong? The output is kind of wired. Thank you!


  • 0
    K
    public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> list = new ArrayList<>();
            if (nums.length < 3) {
                return list;
            }
            Arrays.sort(nums);
            int left;
            int right;
            int current = nums[0] + 1;
            for (int i = 0; i < nums.length - 2; i++) {
                if (nums[i] != current) {
                    current = nums[i];
                    left = i + 1;
                    right = nums.length - 1;
                    while (left < right) {
                        if (nums[i] + nums[left] + nums[right] > 0) {
                            right--;
                        } else if (nums[i] + nums[left] + nums[right] < 0) {
                            left++;
                        } else {
                            ArrayList<Integer> temp = new ArrayList<>();
                            temp.add(nums[i]);
                            temp.add(nums[left]);
                            temp.add(nums[right]);
                            list.add(temp);
                            while (left < right && nums[left+1] == nums[left]) {
                                left++;
                            }
                            left++;
                            while (left < right && nums[right-1] == nums[right]) {
                                right--;
                            }
                            right--;
                        }
                    }
                } else {
                    i++;
                }
            }
            return list;
    

    When the input is [-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0], my output is [[-5,1,4],[-4,0,4],[-4,1,3],[-2,-2,4],[-2,1,1]], but the expected output is [[-5,1,4],[-4,0,4],[-4,1,3],[-2,-2,4],[-2,1,1],[0,0,0]]. I don't know how do I get the most part correct except the last [0,0,0]. Can anyone help me, thanks.


Log in to reply
 

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