[Leetcode][016] 3Sum Closest (Java)

题目: https://leetcode.com/problems/3sum-closest/

【标签】Array; Two Pointers

【个人分析】

  这道题和它的姊妹题 3Sum 非常类似, 就不再多说了,具体一些的分析可以参考 [Leetcode][015] 3Sum

 

 1 public class Solution {
 2     public int threeSumClosest(int[] nums, int target) {
 3         int result = target;
 4         int len = nums.length;
 5         if (len < 3) {
 6             return 0;
 7         }
 8         Arrays.sort(nums);
 9         for (int i = 0; i < len; i++) {
10             int number = nums[i];
11             
12             int leftIndex = i + 1;
13             int rightIndex = len - 1;
14             while (leftIndex < rightIndex) {
15                 int threeSum = number + nums[leftIndex] + nums[rightIndex];
16                 if (threeSum == target) {
17                     // best result found!
18                     return target;
19                 } else {
20                     // update global result
21                     if ( result == target || 
22                             Math.abs(target - threeSum) < Math.abs(target - result)) {
23                         result = threeSum;
24                     }
25                     if (threeSum < target) {
26                         while (leftIndex < rightIndex && 
27                                 nums[leftIndex] == nums[leftIndex + 1]) {
28                             leftIndex++;
29                         }
30                         leftIndex++;
31                     } else {
32                         while (leftIndex < rightIndex && 
33                                 nums[rightIndex] == nums[rightIndex - 1]) {
34                             rightIndex--;
35                         }
36                         rightIndex--;
37                     }
38                 }
39             }
40         }
41         return result;
42     }
43 
44 }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。