?LeetCode刷題實(shí)戰(zhàn)18: 四數(shù)之和
算法的重要性,我就不多說(shuō)了吧,想去大廠,就必須要經(jīng)過(guò)基礎(chǔ)知識(shí)和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號(hào)后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問(wèn)題叫做四數(shù)之和?,我們先來(lái)看題面:
https://leetcode-cn.com/problems/4sum/
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
題意
樣例
給定數(shù)組 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
滿足要求的四元組集合為:
[
??[-1, 0, 0, 1],
??[-2, -1, 1, 2],
??[-2, 0, 0, 2]
]
題解
class?Solution{
??public:
??vector<vector<int>> fourSum(vector<int>& nums, int?target) {
????????sort(nums.begin(),nums.end());
????????vector<vector<int> > res;
????????if(nums.size()<4)
????????return?res;
????????int?a,b,c,d,_size=nums.size();
????????for(a=0;a<=_size-4;a++){
??????????if(a>0&&nums[a]==nums[a-1]) continue; //確保nums[a] 改變了
??????????for(b=a+1;b<=_size-3;b++){
????????????if(b>a+1&&nums[b]==nums[b-1])continue; //確保nums[b] 改變了
????????????c=b+1,d=_size-1;
????????????while(c??????????????if(nums[a]+nums[b]+nums[c]+nums[d] ??????????????????c++;
??????????????else?if(nums[a]+nums[b]+nums[c]+nums[d]>target)
??????????????????d--;
??????????????else{
????????????????res.push_back({nums[a],nums[b],nums[c],nums[d]});
????????????????while(c1]==nums[c]) //確保nums[c] 改變了
????????????????????c++;
????????????????while(c-1]==nums[d]) //確保nums[d] 改變了
????????????????????d--;
????????????????c++;
????????????????d--;
??????????}
????????}
??????}
????}
????return?res;
????}
};
作者:misakasagiri-2
鏈接:https://leetcode-cn.com/problems/4sum/solution/shuang-zhi-zhen-jie-fa-can-zhao-san-shu-zhi-he-ge-/
今天的文章就到這里,如果覺(jué)得有所收獲,請(qǐng)順手點(diǎn)個(gè)在看或者轉(zhuǎn)發(fā)吧,你們的支持是我最大的動(dòng)力。
上期推文:
LeetCode刷題實(shí)戰(zhàn)1:在數(shù)組上遍歷出花樣
LeetCode刷題實(shí)戰(zhàn)2:用鏈表模擬加法
LeetCode刷題實(shí)戰(zhàn)3:最長(zhǎng)不重復(fù)子串
LeetCode刷題實(shí)戰(zhàn)4:兩個(gè)正序數(shù)組的中位數(shù)
LeetCode刷題實(shí)戰(zhàn)5:判斷回文子串
LeetCode刷題實(shí)戰(zhàn)6:Z字形變換
LeetCode刷題實(shí)戰(zhàn)7:整數(shù)反轉(zhuǎn)
LeetCode刷題實(shí)戰(zhàn)8:字符串轉(zhuǎn)換整數(shù)
LeetCode刷題實(shí)戰(zhàn)9:求解回文數(shù)
LeetCode刷題實(shí)戰(zhàn)10:字符串正則匹配
LeetCode刷題實(shí)戰(zhàn)11: 盛最多水的容器
LeetCode刷題實(shí)戰(zhàn)12: 整數(shù)轉(zhuǎn)羅馬數(shù)字
LeetCode刷題實(shí)戰(zhàn)13: 羅馬數(shù)字轉(zhuǎn)整數(shù)
LeetCode刷題實(shí)戰(zhàn)14: 最長(zhǎng)公共前綴
LeetCode刷題實(shí)戰(zhàn)15:三數(shù)之和
LeetCode刷題實(shí)戰(zhàn)16: 最接近的三數(shù)之和
LeetCode刷題實(shí)戰(zhàn)17: 電話號(hào)碼的字母組合
