[leetcode]3Sum Closest

至此,终于把LeetCode Old OJ里的132题刷完了,小小的成就。

此题算法简单,就是O(n^2),采用和Two Sum类似的做法就是了。我的代码略有麻烦之处,主要是在函数里判断了一次abs的差值,外面又判断了一次,但总体不影响。

注意,先选定i,然后在i后面的元素做TwoSum,意思是当第一个元素是i时的结果,这样就不会重复。

也有不需要子函数的写法,更简洁:http://www.cnblogs.com/graph/p/3343847.html

public class Solution {
    public int threeSumClosest(int[] num, int target) {
        Arrays.sort(num);
        int len = num.length;
        int diff = target - (num[0] + num[1] + num[2]);
        for (int i = 0; i < len - 2; i++)
        {
            int tmp = twoSumClosest(num, target - num[i], i + 1);
            if (tmp == 0) return target;
            if (Math.abs(tmp) < Math.abs(diff))
            {
                diff = tmp;
            }
        }
        return target - diff;
    }
    
    private int twoSumClosest(int[] num, int target, int l)
    {
        int r = num.length - 1;
        int diff = target - num[l] - num[r];
        while (l < r)
        {
            int sum = num[l] + num[r];
            if (sum == target)
            {
                return 0;
            }
            else
            {
                int tmp = target - num[l] - num[r];
                if (Math.abs(tmp) < Math.abs(diff))
                {
                    diff = tmp;
                }
                if (sum > target)
                {
                    r--;
                }
                else
                {
                    l++;
                }
            }
        }
        return diff;
    }
}

  

原文地址:https://www.cnblogs.com/lautsie/p/3356295.html