Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
016.3sum_closest (Medium)
links:
Title: https://oj.leetcode.com/problems/3sum-closest/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
Finds three numbers in a given sequence, making and closest to target.
Analysis:
With 015. 3Sum (Medium) is similar, even simpler.
Or the first sort, and then left and right clamping force.
Code:
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 Numberint k = len-1;//Third Numberwhile (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< C4/>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 retur n RET
[Leetcode] 016. 3Sum Closest (Medium) (C++/java/python)