国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 六枝特区| 福安市| 安西县| 彭州市| 视频| 玉林市| 汉川市| 兴城市| 灵石县| 蕲春县| 津南区| 漯河市| 民权县| 荆州市| 彭泽县| 高安市| 湖州市| 阿荣旗| 察哈| 攀枝花市| 南宫市| 武冈市| 综艺| 宁晋县| 垣曲县| 通河县| 宽城| 绥滨县| 绍兴市| 灵石县| 二手房| 岐山县| 永善县| 延津县| 榆社县| 全南县| 德州市| 龙山县| 百色市| 永福县| 辰溪县|