国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 普格县| 石泉县| 宿州市| 彰化市| 闸北区| 新营市| 多伦县| 余干县| 凉城县| 文成县| 阜康市| 虞城县| 遂宁市| 钟祥市| 兰坪| 田东县| 内乡县| 太仓市| 台南县| 桦南县| 阳春市| 黑山县| 龙海市| 东阿县| 自贡市| 天台县| 长海县| 云霄县| 逊克县| 灵石县| 望江县| 托克托县| 板桥市| 陵水| 婺源县| 丹巴县| 德江县| 凌海市| 新竹县| 迭部县| 乐山市|