码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 日记 3sumclosest java

时间:2016-07-20 19:16:02      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

整体思路为将threeSum将为twoSum即可

public int solution(int[] nums, int target) {
        if (nums.length == 3) {
            return nums[0] + nums[1] + nums[2];
        } else {
            Arrays.sort(nums);
            int r = 10000;//此两处10000为省事而设,如果严谨应该大致找到其中的一个较大距离
            int distance = 10000;
            for (int i = 0; i < nums.length; i++) {
                int[] temarray = new int[nums.length - 1];
                System.arraycopy(nums, 0, temarray, 0, i);
                System.arraycopy(nums, i + 1, temarray, i, nums.length - i - 1);
                int tem = twoSumClosest(temarray, target - nums[i]) + nums[i];
                int temdistance = tem - target;
                if (temdistance < 0) {
                    temdistance = -temdistance;
                } else if (temdistance == 0) {
                    return tem;
                }
                if (temdistance < distance) {
                    r = tem;
                    distance = temdistance;
                }
            }
            return r;
        }
    }

    private int twoSumClosest(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        int min = nums[r] + nums[l];
        int distance;
        if (min - target > 0) {
            distance = min - target;
        } else {
            distance = target - min;
        }
        while (l < r) {
            if (nums[l] + nums[r] == target)
                return nums[l] + nums[r];
            if (nums[l] + nums[r] < target) {
                if (target - (nums[l] + nums[r]) < distance) {
                    min = nums[l] + nums[r];
                    distance = target - (nums[l] + nums[r]);
                }
                l++;
                continue;
            }
            if (nums[l] + nums[r] > target) {
                if ((nums[l] + nums[r]) - target < distance) {
                    min = nums[l] + nums[r];
                    distance = (nums[l] + nums[r]) - target;
                }
                r--;
                continue;
            }
        }
        return min;
    }

 

leetcode 日记 3sumclosest java

标签:

原文地址:http://www.cnblogs.com/aksdenjoy/p/5689190.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!