首页 > 技术文章 > leetcode 日记 3sumclosest java

aksdenjoy 2016-07-20 17:42 原文

思路一为遍历:

public int thirdSolution(int[] nums, int target) {
        int result = nums[0] + nums[1] + nums[2];
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            int start = i + 1, end = nums.length - 1;
            while (start < end) {
                int tmp = nums[i] + nums[start] + nums[end];
                if (tmp < target) {
                    start++;
                }
                if (tmp > target) {
                    end--;
                }
                if (tmp == target) {
                    return tmp;
                }
                if (Math.abs(tmp - target) < Math.abs(result - target)) {
                    result = tmp;
                }
            }
        }
        return result;
    }

 

整体思路二为将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;
    }

本质上讲两种思路没有区别

推荐阅读