16. 3Sum Closest

import java.util.Arrays;

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int size=nums.length;
        int res=0;
        if(size<3)
            return 0;
        if(size==3)
            return nums[0]+nums[1]+nums[2];
        
        //基本思想,先肯定目標位置,以後定義兩個遊標進行查找
        Arrays.sort(nums);
        boolean start=true;
        boolean isGot=false;
        
        for(int i=0;i<size;i++)
        {
            if(isGot==true)
                break;
            int pre=i+1;
            int back=size-1;
            while(pre<back)
            {
                int temp=nums[i]+nums[pre]+nums[back];
                if(start==true)
                {
                    res=temp;
                    start=false;
                }
                if(temp==target)
                {
                    //代表已經找到了目標的須要的
                    res=temp;
                    isGot=true;
                    break;
                }
                else if(temp<target)
                {
                    //當前的求和比目標小
                    if(target-temp<Math.abs(target-res))
                        res=temp;
                    pre++;
                    
                }
                else
                {
                    //當前的求和比目標大
                    if(temp-target<Math.abs(target-res))
                        res=temp;
                    back--;
                }
            }
        }
        
        return res;
    }
}
相關文章
相關標籤/搜索