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

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

LeetCode 18. 4Sum

2019-11-08 18:23:37
字體:
供稿:網(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]]answer:

class Solution {public:    vector<vector<int>> fourSum(vector<int>& nums, int target) {        sort(nums.begin(),nums.end());        int sum = 0;        int first, second,third,forth;        //int PReFirst, preSecond,preThird,preForth;        vector<vector<int>> result;        for(first = 0; first < nums.size(); first ++){            if(first > 0 ){                while(nums[first] == nums[first - 1]) {                    first ++;                }            }            //preFirst = nums[first];            for(second = first + 1; second < nums.size(); second ++){                if(second - first > 1 ){                    while(nums[second] == nums[second - 1]) {                        second ++;                    }                }            //preFirst = nums[first];                third = second + 1;                forth = nums.size() - 1;                while(third < forth){                    sum = nums[first] + nums[second] + nums[third] + nums[forth];                    if(sum < target) third ++;                    else if(sum > target) forth --;                    else{                        vector<int> temp;                        temp.push_back(nums[first]);                        temp.push_back(nums[second]);                        temp.push_back(nums[third]);                        temp.push_back(nums[forth]);                        result.push_back(temp);                        third ++;                        while(nums[third] == nums[third - 1]) third ++;                        forth --;                        while(nums[forth] == nums[forth + 1]) forth --;                    }                }            }        }        return result;    }};


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 祁东县| 息烽县| 昌图县| 万荣县| 施秉县| 玉田县| 镇安县| 凤阳县| 海原县| 昌江| 黄骅市| 依兰县| 栾城县| 澳门| 罗江县| 永安市| 乌兰浩特市| 梅河口市| 扶风县| 哈密市| 巧家县| 宜兴市| 舟曲县| 衡水市| 泸水县| 遂昌县| 偏关县| 广灵县| 固始县| 正阳县| 铜梁县| 响水县| 蚌埠市| 涟源市| 秦皇岛市| 巴东县| 娱乐| 岱山县| 读书| 古交市| 金堂县|