leetcode 3Sum Closest 难度系数3 3.7
来源:互联网 发布:域名收费标准 编辑:程序博客网 时间:2024/06/15 22:47
Question:
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
public class Solution {private int result;private int state;public int threeSumClosest(int[] num, int target) {result = 0;Arrays.sort(num);state = 0;if (num.length < 3) {return result;}int length = num.length - 1;for (int i = 0; i <= length - 2; i++) {if (i != 0 && (num[i] == num[i - 1])) {continue;}subThreeSum(num, i, i + 1, length, target);}return result;}private void subThreeSum(int[] num, int i, int first, int last, int target) {while (first < last) {int sum = num[i] + num[first] + num[last];if (state == 0|| Math.abs(sum - target) < Math.abs(result - target)) {result = sum;state = 1;}if (sum <= target) {first++;while (first < last && num[first] == num[first - 1]) {first++;}} else {last--;while (first < last && num[last] == num[last + 1]) {last--;}}}}}
0 0
- leetcode 3Sum Closest 难度系数3 3.7
- leetcode 3Sum 难度系数 3.6
- leetcode 4Sum 难度系数3 3.9
- leetcode JAVA Combination Sum 难度系数3 3.13
- leetcode JAVA Minimum Path Sum 难度系数3 3.22
- 题解——Leetcode 16. 3Sum Closest 难度:Medium
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- [LeetCode] 3Sum Closest
- 【leetcode】3Sum Closest
- leetcode Container With Most Water 难度系数3 3.4
- opencv2.4.8在win7下无法打开摄像头,或者摄像头灰色图像的解决方案
- HDU1143Tri Tiling
- leetcode Integer to Roman 难度系数3 3.5
- leetcode 3Sum 难度系数 3.6
- leetcode 3Sum Closest 难度系数3 3.7
- 黑马程序员--命名空间和索引器小结
- leetcode 4Sum 难度系数3 3.9
- 排序二叉树的构造与遍历
- 二叉搜索树
- C++ 多重继承
- 12款免费与开源的NoSQL数据库介绍
- 轻松搞定面试中的二叉树题目
- libevent 多线程