首页 > 其他 > 详细

LeetCode_16 3SumCloest

时间:2018-05-27 20:17:03      阅读:210      评论:0      收藏:0      [点我收藏+]

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).

 1 public int threeSumClosest(int[] nums, int target) {
 2         Arrays.sort(nums);
 3         int sum = nums[0] + nums[1] + nums[2];
 4         int diff = Math.abs(sum - target);
 5         for (int i = 0; i < nums.length - 2; i++) {
 6             if (i != 0 && nums[i] == nums[i - 1])
 7                 continue;
 8             int j = i + 1;
 9             int k = nums.length - 1;
10             while (k > j) {
11                 int aa = nums[i] + nums[j] + nums[k];
12                 int newDiff = Math.abs(aa - target);
13                 if (newDiff < diff) {
14                     diff = newDiff;
15                     sum = aa;
16                 }
17                 if (aa < target) {
18                     j++;
19                 } else {
20                     k--;
21                 }
22             }
23         }
24         return sum;
25     }

 

LeetCode_16 3SumCloest

原文:https://www.cnblogs.com/ntbww93/p/9096989.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!