码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode_16 3SumCloest

时间:2018-05-27 20:28:35      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:lse   while   code   public   AC   put   i++   tin   targe   

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

标签:lse   while   code   public   AC   put   i++   tin   targe   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!