25 ms Java Solution. Can someone please look into code to optimize ?


  • 0

    public class Solution {
    public int threeSumClosest(int[] nums, int target) {

        int ans=99999;
        int f=0;
        int total=0;
        for(int i=0;i<nums.length-2;i++){
    inner:for(int j=i+1,k=nums.length;j<nums.length-1;)
         {   k--;
          if(k==j)
              {
               j++;
              k=nums.length;
              continue inner;
             }
          //   System.out.println(i+" "+j+" "+k+" ");
              total=nums[i]+nums[j]+nums[k];
                     if(total>target){
                         if(total-target<ans&&total-target>=0)
                         {
                             ans=total-target;
                             f=total;
                             
                         }
                     }
                     else
                     {  if(target==total)
                         return total;
                         if(target-total<ans&&target-total>=0)
                         {
                             ans=target-total;
                             f=total;
                         }
           }
           
         }  }
         return f;
      
    }
    

    }


Log in to reply
 

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