O^2 JAVA using hashtable


  • 0
    T
    public class Solution {
    public boolean findTarget(int[] nums, int target, int[] hashtable,int min){
        for(int i=0;i<nums.length;i++){
            for(int j=i+1;j<nums.length;j++){
                if(target-nums[i]-nums[j]-min>=0&&target-nums[i]-nums[j]-min<hashtable.length){
                    if(nums[i]==nums[j]){
                        if(nums[i]==target-nums[i]-nums[j]){
                            if(hashtable[target-nums[i]-nums[j]-min]>=3)return true;
                        }
                        else if(hashtable[target-nums[i]-nums[j]-min]>=1)return true;
                    }
                    else if(nums[i]==target-nums[i]-nums[j]||nums[j]==target-nums[i]-nums[j]){
                        if(hashtable[target-nums[i]-nums[j]-min]>=2)return true;
                    }
                    else if(hashtable[target-nums[i]-nums[j]-min]>=1)return true;
                }
            }
        }
        return false;
    }
    public int threeSumClosest(int[] nums, int target) {
       int min=nums[0];
       int max=nums[0];
       for(int i=0;i<nums.length;i++){
           min=nums[i]<min?nums[i]:min;
           max=nums[i]>max?nums[i]:max;
       }
       int[] hashtable = new int[max-min+1];
       for(int i=0;i<hashtable.length;i++){
           hashtable[i]=0;
       }
        for(int i=0;i<nums.length;i++){
            hashtable[nums[i]-min]++;
    }
    int i=1;
    if(findTarget(nums,target,hashtable,min))return target;
    while(true){
         if(findTarget(nums,target+i,hashtable,min))return target+i;
          if(findTarget(nums,target-i,hashtable,min))return target-i;
          i++;
    }
    

    }
    }


Log in to reply
 

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