n^2 JAVA Solution beats 99%


  • 0
    F
    public class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            
            List<List<Integer>> res = new LinkedList<List<Integer>>();
            Arrays.sort(nums);
            int len = nums.length;
            for (int i = 0; i < len-2; i++) {
                if (i > 0 && nums[i] == nums[i-1])
                    continue;
                int beg = i+1, end = len-1;
                int target = -nums[i];
                while (beg < end) {
                    
                    if (nums[beg]+nums[end] > target)
                        end--;
                    else if (nums[beg]+nums[end] < target)
                        beg++;
                    else {
                        List<Integer> newList = new LinkedList<Integer>();
                        newList.add(nums[i]);
                        newList.add(nums[beg]);
                        newList.add(nums[end]);
                        res.add(newList);
                        while (beg < end && nums[beg] == nums[beg+1])
                            beg++;
                        while (beg < end && nums[end] == nums[end-1])
                            end--;
                        beg++;
                        end--;
                    }
                }
            }
            
            return res;
        }
    }
    

Log in to reply
 

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