标签:leetcode c++ java python 算法
索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github:
https://github.com/illuz/leetcode
题目: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