[LeetCode两数之和 II ]| 刷题打卡
一直有刷题习惯,最近才看到掘金举办了刷题活动,特来参加!,这是此次提交的第2题。
本文正在参与掘金团队号上线活动,点击 查看大厂春招职位
一、题目描述:
描述 给一组整数,问能找出多少对整数,他们的和大于一个给定的目标值。请返回答案。 样例 样例 1:
输入: [2, 7, 11, 15], target = 24
输出: 1
解释: 11 + 15 是唯一的一对
样例 2:
输入: [1, 1, 1, 1], target = 1
输出: 6
挑战
O(1) 额外空间以及 O(nlogn) 时间复杂度
二、思路分析:
方法 | 描述 | 时间复杂度 | 空间复杂度 |
|---|---|---|---|
| 双指针 | 相向双指针,排序,打擂台,求和 | ||
| 第一步 | 满足条件nums[start]+nums[end]>target,则result+=end-start,且同时移动指针end-- | ||
| 第二步 | 不满足条件同时移动指针start++ |
三、AC 代码:
public class Solution {
/**
* fix bug :back conditons is 0
*
* @param nums: an array of integer
* @param target: An integer
* @return: an integer
*/
public int twoSum2(int[] nums, int target) {
// write your code here
if (nums == null || nums.length == 0) {
return 0;
}
Arrays.sort(nums);
int start = 0;
int end = nums.length - 1;
int count = 0;
while (start < end) {
if (nums[start] + nums[end] <= target) {
start++;
} else {
// sum temp result
int size = end - start;
count += size;
end--;
}
}
return count;
}
}
四、总结:
相向双指针,属于双指针的一种,常用语排序、打擂台查找、求和等
- 时间复杂度是,原地查找空间复杂度是
- 双指针的缺点仍然是需要提前排序,实际运用的过程需要事先考虑具体场景是否允许排序