演算法3Sum Closest
- import java.util.Arrays;
- public class ThreeSumClosest {
- private int closest;
- private boolean needInit;
- public int threeSumClosest(int[] num, int target) {
- closest = 0;
- needInit = true;
- Arrays.sort(num);
- int i = 0;
- for (i = 0; i <= num.length - 3; i++) {
- if (i != 0 && num[i] == num[i - 1]) {
- continue;
- }
- judgeAndPut(num, i, i + 1, num.length - 1, target);
- }
- return closest;
- }
- private void judgeAndPut(int[] num, int i, int p, int q, int target) {
- while (p
- int sum = num[i] + num[p] + num[q];
- if (needInit || Math.abs(sum - target)
- closest = sum;
- }
- needInit = false;
- if (sum <= target) {
- p++;
- while (p 1]) {
- p++;
- }
- } else if (sum > target){
- q--;
- while (p 1]) {
- q--;
- }
- }
- }
- }
- public static void main(String[] args) {
- int num[] = {0,1,2};
- System.out.println(new ThreeSumClosest().threeSumClosest(num, 3));
- }
- }
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29012686/viewspace-1153205/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- Leetcode 3Sum ClosestLeetCode
- Leetcode 16 3Sum ClosestLeetCode
- 3Sum Closest leetcode javaLeetCodeJava
- [LeetCode] 3Sum Closest 最近三數之和LeetCode
- LeetCode 3Sum Closest(016)解法總結LeetCode
- 演算法3Sum演算法
- 迭代最近點演算法 Iterative Closest Points演算法
- jQuery closest()jQuery
- 演算法學習之一:3SUM變體演算法
- 秒殺 2Sum 3Sum 4Sum 演算法題演算法
- Leetcode 3SumLeetCode
- [LintCode] 3Sum Smaller
- Leetcode 15 3SumLeetCode
- 15. 3Sum(圖解)圖解
- LintCode-Subarray Sum Closest
- Leetcode-3Sum ClosestLeetCode
- [LeetCode] 3Sum 三數之和LeetCode
- [LeetCode] 681. Next Closest TimeLeetCode
- closest()函式parent()函式的區別函式
- LeetCode-Closest Binary Search Tree ValueLeetCode
- LeetCode-Closest Binary Search Tree Value IILeetCode
- LeetCode 3Sum(015)解法總結LeetCode
- P4423 [BJWC2011] 最小三角形 與 SP7209 CLOSEST - Closest Triplet
- [譯] 使用 closest() 函式獲取正確的 DOM 元素函式
- closest()、parents()和parent()方法的區別簡單介紹
- 【LeetCode從零單排】No15 3SumLeetCode
- LeetCode 272 Closest Binary Tree Traversal II 解題思路LeetCode
- 973. K Closest Points to Origin(Leetcode每日一題-2020.11.09)LeetCode每日一題
- 【演算法】KMP演算法演算法KMP
- 演算法-回溯演算法演算法
- 【JAVA演算法】圖論演算法 -- Dijkstra演算法Java演算法圖論
- 演算法(2)KMP演算法演算法KMP
- 【演算法】遞迴演算法演算法遞迴
- 演算法題:洗牌演算法演算法
- [演算法之回溯演算法]演算法
- Manacher演算法、KMP演算法演算法KMP
- 【演算法】KMP演算法解析演算法KMP
- 介面限流演算法:漏桶演算法&令牌桶演算法演算法