[leetcode]16. 3Sum Closest最接近的三数之和
Posted 程序媛詹妮弗
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]16. 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).
题意:
给定一个数组和一个值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最接近的三数之和的主要内容,如果未能解决你的问题,请参考以下文章