We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。 注意: 答案中不可以包含重复的四元组。 示例: 给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。 满足要求的四元组集合为: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
双指针法
/** * 双指针法 */ var fourSum = function(nums, target) { // #1 排序 nums = nums.sort((a, b) => a - b); const res = []; // #2 记录值 let recordA, recordB, recordC; // #3 遍历数组 for (let i = 0; i < nums.length - 3; i++) { // #4 判断最开始的和 如果大于target 直接跳出循环 if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break; // #5 判断值是否等于之前的值 如果等于 跳过这个值 if (nums[i] === recordA) continue; // #6 遍历接下来的数组 for (let j = i + 1; j < nums.length; j++) { // #7 如果之前的值 和 当前的值 都一致,直接跳过这一轮循环 if (nums[i] === recordA && nums[j] === recordB) continue; // #8 设定两个指针 let start = j + 1, end = nums.length - 1; while (start < end) { // #9 求和 let sum = nums[i] + nums[j] + nums[start] + nums[end]; // #10 �判断和大小 if (sum === target) { // #11 判断前三位是否重复 if (!(nums[i] === recordA && nums[j] === recordB && nums[start] === recordC)) { // #12 记录值,放入结果数组 recordA = nums[i]; recordB = nums[j]; recordC = nums[start]; res.push([nums[i], nums[j], nums[start], nums[end]]); } // #13 两端缩进 start++; end--; } else { // #14 判断和与target的大小,如果大于,end左移;如果小于,start右移 sum > target ? end-- : start++; } } } } return res; };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
题目描述
算法
答案
The text was updated successfully, but these errors were encountered: