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

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

LeetCode 18. 4Sum

2019-11-11 04:38:45
字體:
供稿:網(wǎng)友

描述 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]]

分析 先排序,然后左右夾逼,復(fù)雜度 O(n3),會(huì)超時(shí)。 可以用一個(gè) hashmap 先緩存兩個(gè)數(shù)的和,最終復(fù)雜度 O(n3)。這個(gè)策略也適用于 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()); // 刪除重復(fù)項(xiàng) return result; }};
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 都昌县| 崇仁县| 兖州市| 昆山市| 富宁县| 中方县| 米易县| 奎屯市| 桐柏县| 民和| 阿坝县| 绥化市| 巴南区| 榆林市| 津南区| 泰和县| 滨海县| 徐州市| 承德市| 澄城县| 莱芜市| 叙永县| 山西省| 琼海市| 阳泉市| 汉川市| 西青区| 永吉县| 洛浦县| 板桥市| 普兰店市| 谢通门县| 霸州市| 大名县| 左权县| 五指山市| 赤城县| 临朐县| 扶沟县| 辽源市| 七台河市|