leetcode刷题(30天)-16. 最接近的三数之和

廉价感情. 提交于 2020-03-05 21:45:36
class Solution {
    public int threeSumClosest(int[] nums, int target) {
        if (nums.length==0){return 0;}
            Arrays.sort(nums); //排序
            int distance = nums[0] + nums[1] + nums[2] - target;
            for(int i=0;i<nums.length;i++){
                if(distance==0)break;
                int r=nums.length -1;
                int l= i+1;
                while(l<r){
                    int dis = (nums[l] + nums[r] + nums[i]) - target;
                    if(dis == 0){
                        distance =dis;
                        break;}
                    if(Math.abs(distance) > Math.abs(dis)){
                        distance = dis;
                    }
                    if (dis > 0) r--;
                    else l++;
                }
            }
        return distance + target;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!