why is my solution time limit exceed ? It is 100% O(n^2).


  • 0
    K

    public List<List<Integer>> threeSum(int[] nums) {
    if (nums.length<3)return new ArrayList<List<Integer>>();
    Arrays.sort(nums);
    List<List<Integer>> boys=new ArrayList<List<Integer>>();
    for(int i =0; i<nums.length-2;i++){
    for(int j=i+1,k=nums.length-1;j<k; ){
    if(nums[i]+nums[j]+nums[k]==0){
    List<Integer> boy=new ArrayList<Integer>();
    boy.add(nums[i]);
    boy.add(nums[j]);
    boy.add(nums[k]);
    if (!boys.contains(boy))
    boys.add(boy);
    j++;k--;

            }
            else if(nums[i]+nums[j]+nums[k]>0){
            	k--;
            }
            else if(nums[i]+nums[j]+nums[k]<0){
            	j++;
            } 
            if (k==j) break;
        	}
        }
        return boys;
    }

Log in to reply
 

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