18.4Sum
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了18.4Sum相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/sort' title='sort'>sort solution col 绛変簬 get for tor 3sum tco
缁欏畾涓€涓暟缁勫拰涓€涓洰鏍囨暟瀛楋紝姹傛暟缁勪腑鐨?涓厓绱犱箣鍜岀瓑浜庣洰鏍囨暟瀛楋紝杈撳嚭杩?涓暟瀛楁墍鏈夊彲鑳界殑缁勫悎銆?/p>
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
銆€[-1, 0, 0, 1],
銆€[-2, -1, 1, 2],
銆€[-2, 0, 0, 2]
]
鎬濊矾锛?br />鍜孡eetCode 15. 3Sum 寰堝儚锛屽鐞嗕笂涔熸寜 3Sum澶勭悊銆傚湪 3Sum澶栭潰鍐嶅涓€灞傚惊鐜嵆鍙€?/p>
vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> res; sort(nums.begin(), nums.end()); int n = nums.size(); for (int i = 0; i < n-3; i++) { if (i > 0 && nums[i] == nums[i - 1]) continue; for (int j = i + 1; j < n - 2; j++) { if (j > i + 1 && nums[j] == nums[j - 1]) continue; int l = j + 1, r = n - 1, remain = target - nums[i] - nums[j]; while (l < r) { if (l > j+1 && nums[l] == nums[l - 1]) { l++; continue; } if (nums[l] + nums[r] > remain) r--; else if (nums[l] + nums[r] < remain) l++; else res.push_back({ nums[i],nums[j],nums[l++],nums[r--] }); } } } return res; }
以上是关于18.4Sum的主要内容,如果未能解决你的问题,请参考以下文章
leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和](代码片段