zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    对象拷贝-深拷贝
    eclipse安装桌面快捷方式
    ajax 分页
    单例模式
    过滤器
    ajax参数详解
    json
    反射
    jdbc02
    jdbc --例子7
  • 原文地址:https://www.cnblogs.com/aguai1992/p/5730385.html
Copyright © 2011-2022 走看看