个人记录-LeetCode 16. 3Sum Closest
2016-10-26 21:52
399 查看
问题:
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
问题要求:找到数组中3个数字,使得它们的和最接近目标。
同样,可以采用LeetCode 11. Container With Most Water类似的解法。
代码示例:
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
问题要求:找到数组中3个数字,使得它们的和最接近目标。
同样,可以采用LeetCode 11. Container With Most Water类似的解法。
代码示例:
public class Solution { public int threeSumClosest(int[] nums, int target) { if (nums == null || nums.length < 3) { throw new IllegalArgumentException(); } //首先将数组变为从小到大排序 Arrays.sort(nums); int result = nums[0] + nums[1] + nums[2]; //处理特殊情况 if ((target > 0 && nums[nums.length - 1] < 0) || (target < 0 && nums[0] > 0)) { return result; } int length = nums.length; int firstIndex; int lastIndex; int curr; int diff; int minDiff = Integer.MAX_VALUE; //固定一个数,逐渐增加 for (int i = 0; i < length - 2; ++i) { firstIndex = i + 1; lastIndex = length - 1; //另外两个数以“夹逼”的方式移动 while (firstIndex < lastIndex) { curr = nums[i] + nums[firstIndex] + nums[lastIndex]; diff = target - curr; if (Math.abs(diff) < minDiff) { minDiff = Math.abs(diff); result = curr; } if (diff > 0) { //diff > 0,说明当前的和太小了,增加低位下标 ++firstIndex; } else if (diff < 0){ //diff < 0, 说明当前的和太大了,减小高位下标 --lastIndex; } else { return target; } } } return result; } }
相关文章推荐
- 16. 3Sum Closest leetcode Python 2016 new Season
- LeetCode16. 3Sum Closest
- 个人记录-LeetCode 4.Median of Two Sorted Arrays
- [LeetCode-Java]16. 3Sum Closest
- Leetcode 16. 3Sum Closest (Medium) (java)
- 【LeetCode】16. 3Sum Closest
- 个人记录-LeetCode 9.Palindrome Number
- 个人记录-LeetCode 3.Longest Substring Without Repeating Characters
- 个人记录-LeetCode 2.Add Two Numbers
- 个人记录-LeetCode 7.Reverse Integer
- [LeetCode]16. 3Sum Closest
- 【leetcode】16. 3Sum Closest
- [leetcode] 【数组】16. 3Sum Closest
- LeetCode 16. 3Sum Closest LeetCode 18. 4Sum
- 【leetcode】16. 3Sum Closest
- leetcode 16. 3Sum Closest
- LeetCode 16. 3Sum Closest(最接近的和)
- leetcode 16. 3Sum Closest
- [leetcode]16. 3Sum Closest
- 个人记录-LeetCode 8.String to Integer (atoi)