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

[LeetCode] 016. 3Sum Closest (Medium) (C++/Java/Python)

时间:2015-03-03 20:47:04      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   java   python   算法   

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode


016.3Sum_Closest (Medium)

链接

题目:https://oj.leetcode.com/problems/3sum-closest/
代码(github):https://github.com/illuz/leetcode

题意

在给定数列中找出三个数,使和最接近 target。

分析

015. 3Sum (Medium) 类似,甚至更简单。
还是先排序,再左右夹逼。

代码

C++:

class Solution {
public:
	int threeSumClosest(vector<int> &num, int target) {
		int ret = num[0] + num[1] + num[2];
		int len = num.size();

		sort(num.begin(), num.end());

		for (int i = 0; i <= len - 3; i++) {
			// first number : num[i]
			int j = i + 1;	// second number
			int k = len - 1;	// third number
			while (j < k) {
				int sum = num[i] + num[j] + num[k];
				if (abs(sum - target) < abs(ret - target))
					ret = sum;
				if (sum < target) {
					++j;
				} else if (sum > target) {
					--k;
				} else {
					++j;
					--k;
				}
			}
		}
		return ret;
	}
};


Java:

public class Solution {

    public int threeSumClosest(int[] num, int target) {
        Arrays.sort(num);
        int ret = num[0] + num[1] + num[2];
        int len = num.length;
        for (int i = 0; i <= len - 3; i++) {
            // first number : num[i]
            int j = i + 1;	// second number
            int k = len - 1;	// third number
            while (j < k) {
                int sum = num[i] + num[j] + num[k];
                if (Math.abs(sum - target) < Math.abs(ret - target))
                    ret = sum;
                if (sum < target) {
                    ++j;
                } else if (sum > target) {
                    --k;
                } else {
                    ++j;
                    --k;
                }
            }
        }
        return ret;

    }
}


Python:

class Solution:
    # @return an integer
    def threeSumClosest(self, num, target):
        if not len(num):
            return 0
        ret = num[0] + num[1] + num[2]
        num.sort()
        for i in range(len(num) - 2):
            j = i + 1
            k = len(num) - 1
            while j < k:
                tsum = num[i] + num[j] + num[k]
                if abs(tsum - target) < abs(ret - target):
                    ret = tsum
                if tsum < target:
                    j += 1
                elif tsum > target:
                    k -= 1
                else:
                    j += 1
                    k -= 1
        return ret


[LeetCode] 016. 3Sum Closest (Medium) (C++/Java/Python)

标签:leetcode   c++   java   python   算法   

原文地址:http://blog.csdn.net/hcbbt/article/details/44041791

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