leetcode 15 3sum & leetcode 18 4sum
3sum:
1 class Solution { 2 public: 3 vector<vector<int>> threeSum(vector<int>& nums) { 4 vector<vector<int>>result; 5 vector<vector<int>>::iterator iter; 6 vector<int>Middle; 7 int length=nums.size()-1; 8 sort(nums.begin(),nums.end()); 9 for(int i=0;i<length-1;i++) { 10 int st=i+1,en=length; 11 if(i>0&&nums[i]==nums[i-1])continue; 12 while(st<en) { 13 while(st>i+1&&nums[st-1]==nums[st]) { 14 st++; 15 continue; 16 } 17 while(en<length&&nums[en+1]==nums[en]) { 18 en--; 19 continue; 20 } 21 if(st>=en)break; 22 int temp=nums[st]+nums[en]; 23 if(temp+nums[i]==0) { 24 Middle.push_back(nums[i]); 25 Middle.push_back(nums[st]); 26 Middle.push_back(nums[en]); 27 result.push_back(Middle); 28 Middle.clear(); 29 st++; 30 } 31 else 32 if(temp+nums[i]<0) 33 st++; 34 else 35 if(temp+nums[i]>0) 36 en--; 37 } 38 } 39 return result; 40 } 41 };
4sum:
1 class Solution { 2 public: 3 vector<vector<int>> fourSum(vector<int>& nums, int target) { 4 vector<vector<int>> result; 5 vector<int>MiddResult; 6 if(nums.size()<4)return result; 7 sort(nums.begin(),nums.end()); 8 int length=nums.size(); 9 for(int i=0;i<length-3;i++) { 10 if(i>0&&nums[i]==nums[i-1])continue; 11 for(int j=i+1;j<length-2;j++) { 12 if(j>i+1&&nums[j]==nums[j-1])continue; 13 int st=j+1,en=length-1; 14 while(st<en) { 15 if(st>j+1&&nums[st-1]==nums[st]) { 16 st++; 17 continue; 18 } 19 if(en<length-1&&nums[en+1]==nums[en]) { 20 en--; 21 continue; 22 } 23 int temp=nums[i]+nums[j]+nums[st]+nums[en]; 24 if(temp==target) { 25 MiddResult.push_back(nums[i]); 26 MiddResult.push_back(nums[j]); 27 MiddResult.push_back(nums[st]); 28 MiddResult.push_back(nums[en]); 29 result.push_back( MiddResult); 30 st++; 31 MiddResult.clear(); 32 } 33 else 34 if(temp<target) 35 st++; 36 else en--; 37 } 38 } 39 } 40 return result; 41 } 42 };