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

[leetcode]16. 3Sum Closest最接近的三数之和

时间:2019-04-05 09:13:42      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:元素   --   NPU   value   must   ace   题意   use   code   

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

 

 

题意:

给定一个数组和一个值target,找出其中3个元素,使其加起来最接近target。

 

Solution1:Two Pointers(left and right to meet each other)

1. Sort the array (coz we must check the duplicates) 

2. Lock one pointer and do two sum with the other two 

3. Keep updating the gap between given target with result. The smaller gap is, the closer result is.

 

code:

 1 /*
 2   Time Complexity: O(n^2). For each locked item, we need traverse the rest of array behind such item.  
 3   Space Complexity: O(1).  We only used constant extra space.
 4 */
 5 class Solution {
 6      public int threeSumClosest(int[] nums, int target) {
 7         int result = 0;
 8         int minGap = Integer.MAX_VALUE;
 9         Arrays.sort(nums);
10         for (int i = 0; i < nums.length; i++) {
11             int left = i + 1;
12             int right = nums.length - 1;
13             while (left < right) {
14                 int sum = nums[i] + nums[left] + nums[right];
15                 int gap = Math.abs(target - sum);
16                 // keep updating the gap. The smaller gap is, the closer result is.
17                 if (gap < minGap) {
18                     result = sum;
19                     minGap = gap;
20                 }
21                 // two pointers(left and right to meet each other)
22                 if (sum < target) {
23                     left++;
24                 } else {
25                     right--;
26                 }
27             }
28         }
29         return result;
30     }
31 }

 

[leetcode]16. 3Sum Closest最接近的三数之和

标签:元素   --   NPU   value   must   ace   题意   use   code   

原文地址:https://www.cnblogs.com/liuliu5151/p/10657852.html

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