概述
目录
- 1.三数之和
- 2.四数之和
1.三数之和
15. 三数之和-中等
b站视频-代码随想录
该题不建议使用哈希法,因为题目要求去重,去重的细节比较多,用哈希就相对复杂了。推荐使用排序+双指针
一层for
循环i
(a)+left
(b)+right
( c )
排序+双指针
var threeSum = function(nums) {
let ans=[];
nums.sort((a,b) => a - b);
for(let i = 0;i < nums.length;i++){
if(nums[i] > 0) return ans;
// 对a进行去重时 将i与它的前一位进行比较,是 nums[i]与nums[i-1] 而不是 nums[i]与nums[i+1]
if(i > 0 && nums[i] === nums[i-1]) continue;
let left = i + 1;
let right = nums.length - 1;
while(left < right){
if(nums[i] + nums[left] + nums[right] === 0){
ans.push([nums[i],nums[left],nums[right]]);
while(left < right && nums[right] === nums[--right]);
while(left < right && nums[left] === nums[++left]);
}else if(nums[i] + nums[left] + nums[right] > 0){
right--;
}else{
left++;
}
}
}
return ans;
};
这道题已经做四遍了,再不会就说不过去了…感觉下面这两行去重很妙啊
while(left < right && nums[right] === nums[--right]);
while(left < right && nums[left] === nums[++left]);
nSum通用解法-递归
指路????代码随想录
2.四数之和
18. 四数之和-中等
b站视频-代码随想录
顺着三数之和的思路,其实就是在三数之和外层再套一个for循环。
var fourSum = function(nums, target) {
if(nums.length < 4) return [];
let ans = [];
nums.sort((a,b) => a-b);
for(let i = 0;i < nums.length - 3;i++){
for(let j = i + 1;j < nums.length - 2;j++){
// if(nums[i] > target) return ans;
if(nums[i] == nums[i-1]) continue;
if(j > 1 + i && nums[j] == nums[j-1]) continue;
let num = nums[i] + nums[j];
let l = j + 1,r = nums.length - 1;
while(l < r){
if(nums[l] + nums[r] == target - num){
ans.push([nums[i] , nums[j],nums[l],nums[r]])
while(l<r && nums[l] == nums[++l]);
while(l<r && nums[r] == nums[--r]);
}else if(nums[l] + nums[r] > target - num){
r--;
}else{
l++;
}
}
}
}
return ans;
}
剪枝操作:这里要注意一点,就是数组中有负数,target
也可以是负数,所以不能想当然认为像三数之和那样if(nums[i] > target) return ans;
而应该是if(nums[i] > target && nums[i] > 0 && target > 0) break;
p.s.对比一下代码随想录版????
var fourSum = function(nums, target) {
const len = nums.length;
if(len < 4) return [];
nums.sort((a, b) => a - b);
const res = [];
for(let i = 0; i < len - 3; i++) {
// 去重i
if(i > 0 && nums[i] === nums[i - 1]) continue;
for(let j = i + 1; j < len - 2; j++) {
// 去重j
if(j > i + 1 && nums[j] === nums[j - 1]) continue;
let l = j + 1, r = len - 1;
while(l < r) {
const sum = nums[i] + nums[j] + nums[l] + nums[r];
if(sum < target) { l++; continue}
if(sum > target) { r--; continue}
res.push([nums[i], nums[j], nums[l], nums[r]]);
while(l < r && nums[l] === nums[++l]);
while(l < r && nums[r] === nums[--r]);
}
}
}
return res;
};
最后
以上就是聪慧耳机为你收集整理的leetcode每天5题-Day291.三数之和2.四数之和的全部内容,希望文章能够帮你解决leetcode每天5题-Day291.三数之和2.四数之和所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复