[LeetCode两数和的最接近值] | 刷题打卡
一直有刷题习惯,最近才看到掘金举办了刷题活动,特来参加!此题为第6题。不得不说掘金的主题就是漂亮呀!赞。
本文正在参与掘金团队号上线活动,点击 查看大厂春招职位
一、题目描述:
描述 给定整数数组num,从中找到两个数字使得他们和最接近target,返回两数和与 target 的差的 绝对值。
样例
样例1
输入: nums = [-1, 2, 1, -4] 并且 target = 4
输出: 1
解释:
最小的差距是1,(4 - (2 + 1) = 1).
样例2
输入: nums = [-1, -1, -1, -4] 并且 target = 4
输出: 6
解释:
最小的差距是6,(4 - (- 1 - 1) = 6).
二、思路分析:
方法 | 描述 | 时间复杂度 | 空间复杂度 |
|---|---|---|---|
| 双指针法 | 相向双指针,打擂台法 | ||
| 第一步 | 用临时变量存储差的最小值,用Math.min进行打擂台比较 | ||
| 第二步 | 当前之和小于target,指针右移start+=,当前之和大于target,指针左移end-- |
三、AC 代码:
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 == 0) {
return -1;
}
int sumTemp = Integer.MAX_VALUE;
int start = 0;
int end = nums.length - 1;
Arrays.sort(nums);
while (start < end) {
int ansSum = nums[start] + nums[end];
sumTemp = Math.min(sumTemp, Math.abs(target - ansSum));
if (ansSum < target) {
// currentSum is too small
start++;
} else {
end--;
}
}
return sumTemp;
}
}
四、总结:
从前面五道题目,大家看见两数已经很有感觉了,很容易想到双指针来解决此题。此题的难点是最接近值如何判断,如何存储。初次看到最接近、最大、最小总是很蒙逼,其实做的多了,就很容易转换过来思路——这就是简单的打擂台思想。
- 如何打擂台?
Math.min、Math.max - 比较哪两个参数?
- 临时变量
sumTemp,临时存储上一次最符合题意的值; - 这一轮的
sum,用于和sumTemp比较
- 临时变量
对此题最精简的总结是:相向双指针+打擂台算法