My Java Solution


  • 0
    C
    public class Solution 
    {
        public List<List<Integer>> threeSum(int[] nums) 
        {
            if (nums == null)
                return null;
            Arrays.sort(nums);
            List<List<Integer>> res = new LinkedList<>();
            for (int i = 0; i <nums.length - 2; ++i)
            {
                if (i > 0 && nums[i] == nums[i-1])
                    continue;
                int left = i+1;
                int right = nums.length - 1;
                while(left < right)
                {
                    if (left > i+1 && nums[left] == nums[left-1])
                    {
                        left++;
                        continue;
                    }
                    if (right < nums.length-1 && nums[right] == nums[right+1])
                    {
                        right--;
                        continue;
                    }
                    if (nums[left] + nums[right] == -nums[i])
                    {
                        res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                        left++;
                    }
                    else if (nums[left] + nums[right] < -nums[i])
                    {
                        left++;
                    }
                    else
                    {
                        right--;
                    }
                }
            }
            return res;
        }
    }

Log in to reply
 

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