MCPcopy Create free account
hub / github.com/Blankj/awesome-java-leetcode / Solution

Class Solution

src/com/blankj/medium/_0016/Solution.java:13–39  ·  view source on GitHub ↗

author: Blankj blog : http://blankj.com time : 2018/01/25 desc :

Source from the content-addressed store, hash-verified

11 * </pre>
12 */
13public class Solution {
14 public int threeSumClosest(int[] nums, int target) {
15 int delta = 0x7fffffff, res = 0;
16 Arrays.sort(nums);
17 int len = nums.length - 2;
18 for (int i = 0; i < len; i++) {
19 int left = i + 1, right = nums.length - 1;
20 while (left < right) {
21 int sum = nums[i] + nums[left] + nums[right];
22 int curDelta = Math.abs(sum - target);
23 if (curDelta == 0) return sum;
24 if (curDelta < delta) {
25 delta = curDelta;
26 res = sum;
27 }
28 if (sum > target) --right;
29 else ++left;
30 }
31 }
32 return res;
33 }
34
35 public static void main(String[] args) {
36 Solution solution = new Solution();
37 System.out.println(solution.threeSumClosest(new int[]{-1, 2, 1, -4}, 1));
38 }
39}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected