Leetcode 16 3Sum Closest
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
這個題和Leetcode15的思路基本類似,就是在前面那個題目的基礎上加上了一個判斷求值。
1)
import java.util.*;
public class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int len = nums.length;
if(len < 3){
return 0;
}
int Min = nums[0] + nums[1] + nums[2];
for(int left = 0 ; left < len - 2 ; left++){
int mid = left + 1;
int right = len - 1;
while(mid < right){
int tmp = target - nums[left];
if(Math.abs(Min - target) > Math.abs(tmp - nums[mid] - nums[right]))
Min = nums[mid] + nums[left] + nums[right];
if(nums[mid] + nums[right] == tmp){
return target;
}else if(nums[mid] + nums[right] < tmp){
mid++;
}else{
right--;
}
}
}
return Min;
}
}
時間複雜度:O(n2)
相關文章
- Leetcode 3Sum ClosestLeetCode
- 3Sum Closest leetcode javaLeetCodeJava
- LeetCode 3Sum Closest(016)解法總結LeetCode
- [LeetCode] 3Sum Closest 最近三數之和LeetCode
- 演算法3Sum Closest演算法
- Leetcode 3SumLeetCode
- Leetcode 15 3SumLeetCode
- Leetcode-3Sum ClosestLeetCode
- [LeetCode] 3Sum 三數之和LeetCode
- [LeetCode] 681. Next Closest TimeLeetCode
- LeetCode-Closest Binary Search Tree ValueLeetCode
- LeetCode-Closest Binary Search Tree Value IILeetCode
- LeetCode 3Sum(015)解法總結LeetCode
- 【LeetCode從零單排】No15 3SumLeetCode
- LeetCode 272 Closest Binary Tree Traversal II 解題思路LeetCode
- jQuery closest()jQuery
- 演算法3Sum演算法
- 973. K Closest Points to Origin(Leetcode每日一題-2020.11.09)LeetCode每日一題
- [LintCode] 3Sum Smaller
- 15. 3Sum(圖解)圖解
- LeetCode 162 JavascriptLeetCodeJavaScript
- LintCode-Subarray Sum Closest
- LeetCode 169. Majority ElementLeetCode
- [LeetCode] 1652. Defuse the BombLeetCode
- 迭代最近點演算法 Iterative Closest Points演算法
- closest()函式parent()函式的區別函式
- LeetCode-162-尋找峰值LeetCode
- 【LeetCode】169. 多數元素LeetCode
- Leetcode 166 Fraction to Recurring DecimalLeetCodeFractionDecimal
- Leetcode 165 Compare Version NumbersLeetCode
- 【Leetcode】163. Missing RangesLeetCode
- 【Leetcode】1690. Stone Game VIILeetCodeGAM
- LeetCode 164 最大間距 HERODING的LeetCode之路LeetCode
- Leetcode:1616. 分割兩個字串得到迴文串LeetCode字串
- [LeetCode] 416. Partition Equal Subset SumLeetCode
- Leetcode 168. Excel Sheet Column TitleLeetCodeExcel
- LeetCode-165-比較版本號LeetCode
- LeetCode169求眾數——分治LeetCode