N^2 time exceed


  • 0
    9

    I have the program with O(n^2) time but the result exceed time limit and I have no idea why. Please help TAT
    Here is the code.

    public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        java.util.Arrays.sort(nums);
        List<List<Integer>> re = new ArrayList<List<Integer>>();
        int len = nums.length;
        if(len<3){
            return re;
        }
        for(int i=1;i<len;i++){
            int b = nums[i];
            if(i>1 && nums[i] == nums[i-1]){
                continue;
            }
            int leftCur=0,rightCur = len-1;
            while((leftCur < i)&&(rightCur > i) ){
                int a=nums[leftCur],c = nums[rightCur];
                int sum = a + b + c;
                if(sum == 0){
                    List<Integer> ans = new ArrayList<Integer>();
                    ans.add(a);
                    ans.add(b);
                    ans.add(c);
                    re.add(ans);
                    leftCur++;
                    rightCur--;
                }else if(sum <0){
                    leftCur++;
                }else if(sum >0){
                    rightCur--;
                }
            }
        }
        
        return re;
    }
    

    }


  • 0
    9

    Oh...I know the answer. It turns out I am giving the wrong answers which takes more time. So the OJ return the exceed time limit.


Log in to reply
 

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