Simple easy to understand JAVA solution


  • 3
    A
    public class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if (nums == null || nums.length == 0){
                return res;
            }
            Arrays.sort(nums);
            
            for (int i = 0 ;i < nums.length ;i++){
                if (nums[0] > 0){
                    return res;
                }
                if (i > 0 && nums[i] == nums[i - 1]){
                    continue;
                }
                int left = i+1;
                int right = nums.length - 1;
                int sum = -nums[i];
                while (left < right){
                    if (nums[left] + nums[right] == sum){
                        List<Integer> subList =  new ArrayList<Integer>();
                        subList.add(nums[i]);
                        subList.add(nums[left]);
                        subList.add(nums[right]);
                        res.add(subList);
                        while (left < right && nums[right] == nums[right - 1]){
                            right--;
                        }
                        right--;
                        while (left < right && nums[left] == nums[left+1]){
                            left++;
                        }
                        left++;
                    }
                    else if ((nums[left] + nums[right]) > sum){
                        while (left < right && nums[right] == nums[right - 1]){
                            right--;
                        }
                        right--;
                    }
                    else {
                        while (left < right && nums[left] == nums[left + 1]){
                            left++;
                        }
                        left++;
                    }
                }
            }
            return res;
        }
    }

Log in to reply
 

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