Why do I get Time Limited Exceeded error with my JAVA code?


  • 0
    Y
    public class Solution {
    public List<List<Integer>> threeSum(int[] num) {
        Arrays.sort(num);
        int size=num.length;
        ArrayList<List<Integer>> container = new ArrayList<List<Integer>>();
        if (size<3) return container;
        
        for (int i=0; i<size; i++){
            int sum =0;
            sum+=num[i];
            for (int j=i+1; j<size; j++){
                sum+=num[j];
                for (int k=j+1; k<size;k++){
                    sum+=num[k];
                    if (sum==0){
                        ArrayList<Integer> temp=new ArrayList<Integer>();
                        temp.add(num[i]);
                        temp.add(num[j]);
                        temp.add(num[k]);
                        if (!container.contains(temp)){
                        	container.add(temp);
                        }
                        sum-=num[k];
                    }else{
                        sum-=num[k];
                    }
                    
                }
                sum-=num[j];
            }
            
        }
        return container;
        
    }
    

    }


  • 0
    L

    This code is O(n^3) must be over limited time and no meaning, it could in O(n^2).


Log in to reply
 

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