LintCode Two Sum Closest
2017-02-12 09:14
197 查看
description:
Given an array nums of n integers, find two integers in nums such that the sum is closest to a given number, target.
Return the difference between the sum of the two integers and the target.
Example
Given array nums = [-1, 2, 1, -4], and target = 4.
The minimum difference is 1. (4 - (2 + 1) = 1).
Note:
Two sum and those follow up we can solve them with HashMap and Two Pointer. So we must to identity which one is the best solution to your question.
Given an array nums of n integers, find two integers in nums such that the sum is closest to a given number, target.
Return the difference between the sum of the two integers and the target.
Example
Given array nums = [-1, 2, 1, -4], and target = 4.
The minimum difference is 1. (4 - (2 + 1) = 1).
Note:
Two sum and those follow up we can solve them with HashMap and Two Pointer. So we must to identity which one is the best solution to your question.
public class Solution { /** * @param nums an integer array * @param target an integer * @return the difference between the sum and the target */ public int twoSumClosest(int[] nums, int target) { // Write your code here if (nums == null || nums.length < 2) { return -1; } Arrays.sort(nums); int left = 0; int right = nums.length - 1; int diff = Integer.MAX_VALUE; while (left < right) { if (target > nums[right] + nums[left]) { diff = Math.min(diff, target - nums[right] - nums[left]); left++; } else { diff = Math.min(diff, nums[right] + nums[left] - target); right--; } } return diff; } }
相关文章推荐
- Lintcode: Subarray Sum Closest
- lintcode:Subarray Sum Closest
- lintcode: Subarray Sum Closest
- lintcode Two Sum - Input array is sorted
- LintCode Subarray Sum Closest
- LintCode "Subarray Sum Closest"
- lintcode 两数之和(Two Sum )(Java)
- [Lintcode two-sum]两数之和(python,双指针)
- lintcode: k Sum 解题报告
- LintCode "Continuous Subarray Sum"
- lintcode:2sum
- LeetCode之“散列表”:Two Sum && 3Sum && 3Sum Closest && 4Sum
- LintCode 59. 3Sum Closest
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Google/LintCode:H-Median of two Sorted Array
- LintCode Two Strings Are Anagrams 两个字符串是变位词
- lintcode-medium-Continuous Subarray Sum
- LintCode "Subarray Sum"
- lintcode add-two-numbers 链表求和
- LintCode "Swap Two Nodes in Linked List"