国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

LeetCode 18. 4Sum

2019-11-11 03:26:09
字體:
來源:轉載
供稿:網友

描述 Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

For example, given array S = [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]]

分析 先排序,然后左右夾逼,復雜度 O(n3),會超時。 可以用一個 hashmap 先緩存兩個數的和,最終復雜度 O(n3)。這個策略也適用于 3Sum 。

class Solution {public: vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> result; if (nums.size() < 4) return result; sort(nums.begin(), nums.end()); auto last = nums.end(); for (auto a = nums.begin(); a < PRev(last, 3); ++a) { for (auto b = next(a); b < prev(last, 2); ++b) { auto c = next(b); auto d = prev(last); while (c < d) { if (*a + *b + *c + *d < target) ++c; else if (*a + *b + *c + *d > target) --d; else { result.push_back({*a, *b, *c, *d}); ++c; --d; } } } } sort(result.begin(), result.end()); result.erase(unique(result.begin(), result.end()), result.end()); // 刪除重復項 return result; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 商洛市| 松潘县| 阿克陶县| 丰台区| 林州市| 定西市| 睢宁县| 视频| 临漳县| 东城区| 响水县| 静安区| 营山县| 华阴市| 大姚县| 靖宇县| 新河县| 安化县| 崇仁县| 五家渠市| 含山县| 吴旗县| 嘉善县| 榆林市| 靖边县| 奉化市| 马山县| 阿鲁科尔沁旗| 吉林市| 昌黎县| 察雅县| 修武县| 宁武县| 海晏县| 壤塘县| 横峰县| 浑源县| 阿拉善盟| 平邑县| 华池县| 彭山县|