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 Closest(016)解法總結LeetCode
- Leetcode 15 3SumLeetCode
- [LeetCode] 681. Next Closest TimeLeetCode
- LeetCode 3Sum(015)解法總結LeetCode
- LeetCode 272 Closest Binary Tree Traversal II 解題思路LeetCode
- 973. K Closest Points to Origin(Leetcode每日一題-2020.11.09)LeetCode每日一題
- HDU 4347 The Closest M Points
- 564-Find the Closest Palindrome
- [LintCode] 3Sum Smaller
- 259. 3Sum Smaller
- 15. 3Sum(圖解)圖解
- P4423 [BJWC2011] 最小三角形 與 SP7209 CLOSEST - Closest Triplet
- 15+18、3Sum 4Sum
- LeetCode 刷題記錄(16、17、18)—Java語言LeetCodeJava
- Q16 LeetCode203 移除連結串列元素LeetCode
- 【leetcode】劍指 Offer 16. 數值的整數次方LeetCode
- 564. Find the Closest Palindrome, 2468. Split Message Based on LimitMIT
- [譯] 使用 closest() 函式獲取正確的 DOM 元素函式
- 演算法學習之一:3SUM變體演算法
- 秒殺 2Sum 3Sum 4Sum 演算法題演算法
- leetcode演算法題解(Java版)-16-動態規劃(單詞包含問題)LeetCode演算法Java動態規劃
- 16
- JDK 16:Java 16的新功能 - InfoWorldJDKJava
- “16*16逐行式順向陰碼”轉“16*16列行式逆向陰碼”字模C程式碼C程式
- 5/16
- 6/16
- 【LeetCode】如何學習LeetCode?LeetCode
- MDS100-16-16-ASEMI三相整流模組MDS100-16
- 魅族16與魅族16 Plus全面評測 魅族16值得買嗎?
- vue16Vue
- 2024/05/16
- 2024 3 16
- 11.15-16
- day16
- 2024/8/16
- 9月16
- utf16be
- chapter16APT