share my solution


  • 0
    L
    # code block 
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        for (int i=0;i<nums.length-2;i++){
            int first = i;
            int second = i+1;
            int last = nums.length-1;
            if (first!=0 && nums[first] == nums[first-1]){
                continue;
            }
            while (second < last){
                if (second != i+1 && nums[second] == nums[second-1]){
                    second ++;
                    continue;
                }
                if (last != nums.length-1 && nums[last] == nums[last+1]){
                    last--;
                    continue;
                }
                int sum = nums[first] + nums[second] + nums[last];
                if (sum > 0){
                    last--;
                }
                if (sum <0) {
                    second++;
                }
                if (sum==0){
                    result.add(Arrays.asList(nums[first], nums[second], nums[last]));
                    last--;
                }
            }
        }
        return result;        
    }

Log in to reply
 

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