Time Limit E


  • 0

    public List<List<Integer>> threeSum(int[] nums) {

        List<List<Integer>> sums = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        int n = nums.length;
        for (int i=0; i< n; i++) {
            int start=i+1; int end=n-1;
            while(start < end) {
    
                if(nums[start] + nums[end] > -nums[i]) {
                    end--;
                }
                else if (nums[start] + nums[end] < -nums[i]) {
                    start++;
                }
                else {
                    List<Integer> s = new ArrayList<Integer>();
                    s.add(nums[i]);
                    s.add(nums[start]);
                    s.add(nums[end]);
                    end--;
    
                    if (!sums.contains(s)) {
                        sums.add(s);
                    }
    
                }
            }
        }
    
         
        return sums;
    
    }

  • 0

    @ankit_impression-yahoo-com

    Two things you can do better next time:

    • format your code properly using ```
    • present your programming language which will be easier for others to help you out

  • 0

    @ankit_impression-yahoo-com Your solution is fixed now. there are three issues in your previous solution. Check them yourself, if you need any extra help, let me know.

    public List<List<Integer>> threeSum(int[] nums) {
    
        List<List<Integer>> sums = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        int n = nums.length;
        for (int i=0; i< n; i++) {
            if(i>0 && nums[i]==nums[i-1]) continue;
            int start=i+1; int end=n-1;
            while(start < end) {
    
                if(nums[start] + nums[end] > -nums[i]) {
                    end--;
                }
                else if (nums[start] + nums[end] < -nums[i]) {
                    start++;
                }
                else {
                    List<Integer> s = new ArrayList<Integer>();
                    s.add(nums[i]);
                    s.add(nums[start++]);
                    s.add(nums[end--]);
                    while(start<end && nums[start]==nums[start-1]) start++;
                    while(start<end && nums[end]==nums[end+1]) end--;
                    sums.add(s);
                }
            }
        }
    
         
        return sums;
    
    }
    

Log in to reply
 

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