[LeetCode两数之和 - 不同组成] | 刷题打卡
一直有刷题习惯,最近才看到掘金举办了刷题活动,特来参加!此题为第7题。不得不说掘金的主题就是漂亮呀!赞。
虽然是第7题了,但仍然属于双指针的题目,看见双指针有没有吐呢,别急,我们练会为止。
本文正在参与掘金团队号上线活动,点击 查看大厂春招职位
一、题目描述:
给一整数数组, 找到数组中有多少组 不同的元素对 有相同的和, 且和为给出的 target 值, 返回对数.
例1:
输入: nums = [1,1,2,45,46,46], target = 47
输出: 2
解释:
1 + 46 = 47
2 + 45 = 47
例2:
输入: nums = [1,1], target = 2
输出: 1
解释:
1 + 1 = 2
二、思路分析:
| 方法 | 描述 | 时间复杂度 | 空间复杂度 |
|---|---|---|---|
| 双指针 | 先排序后双指针 | ||
| 双指针 | 使用临时变量count记录符合target的组合数量 | ||
| 双指针 | 跳过重复的元素值 |
三、AC 代码:
import java.util.Arrays;
public class TwoSum {
public static void main(String[] args) {
int[] nums = new int[] { 1, 0, -1 };
int target = 0;
System.out.print(twoSum(nums, target));
}
public static int twoSum(int[] nums, int target) {
// back conditions
if (nums == null || nums.length < 2) {
// why need < 2?
return 0;
}
Arrays.sort(nums);
int left = 0;
int right = nums.length - 1;
int count = 0;
while (left < right) {
int currentSum = nums[left] + nums[right];
if (currentSum == target) {
count++;
left++;
right--;
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
} else if (currentSum > target) {
right--;
} else {
left++;
}
}
return count;
}
}
四、总结:
与前面的双指针查找不同,此题需要在相向查找的过程中,继续查找,直至结束,使用count计数的方式,来记录结果。细心的朋友会问了,这题只考一个count计数这么简单吗? 答:当然不是,还考察以下情况:
- 重复元素的过滤,如何跳过相同元素
nums[right]==nums[right+1] - 数组越界的边界处理,
left<right这道题的收获是如何处理相同元素,如何计数不同组成。