Why my code exceed the time limit


  • 0
    D
    public static int threeSumClosest(int[] num, int target) 
    {
    		int sum = 0;
    		Arrays.sort(num);
    		for(int i = 0;i < num.length; i++){
    			int j = i + 1;
    			int k = num.length - 1;
    			while(j < k ){
    				sum = num[i] + num[j] + num[k];
    				if(i+1 == j && k-1 == j)
    					return sum;
    				
    				if(sum < target){
    					if(j < k )j++;
    				}
    					
    				else if(sum > target){
    					if(k > j ) k--;
    				}else{    //相等的情况
    					return sum;
    				}
    				
    				
    			}
    			
    		}
    		return sum;
            
        }

  • 0
    H

    First, your logic is wrong. The closest doesn't mean k - 1 = j.
    Second, after your second if (sum < target), j++. If there's no case that sum == target. It will never return from your first if case because i + 1 != j.


Log in to reply
 

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