方法:哈希表
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
unordered_map<int, int> vis;
int res = 0;
for (int a : nums1)
for (int b : nums2)
++vis[a + b];
for (int c : nums3)
for (int d : nums4)
if (vis.find(-d-c) != vis.end()) res += vis[-c-d];
return res;
}
};
$时间复杂度O(),空间复杂度O(n);
方法:哈希表
class Solution {
#define maxn 100010
public:
bool canConstruct(string ransomNote, string magazine) {
int a[maxn];
memset(a, 0, sizeof a);
if (ransomNote.size() > magazine.size()) return false;
for (char c : magazine) ++a[c];
for (char c : ransomNote) {
--a[c];
if (a[c] < 0) return false;
}
return true;
}
};
$时间复杂度O(n),空间复杂度O(n);
方法:排序+双指针
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>>ret;
int i, j, k;
int n = nums.size();
sort(nums.begin(), nums.end());
ret.reserve(n > 1024 ? 1024 : n);
if(nums.size() < 3 || nums[0] > 0 || nums[n-1] < 0) {
return ret;
}
if(!nums[0] && !nums[n-1]) {
return {{0, 0, 0}};
}
for(i = 0; i < n - 2; ++i) {
if(i && nums[i] == nums[i-1]) {
continue;
}
if(nums[i] > 0) {
break;
}
j = i + 1;
k = n - 1;
while(j < k) {
int target = nums[i] + nums[j] + nums[k];
if(target > 0) {
--k;
}else if(target < 0) {
++j;
}else {
ret.push_back({nums[i], nums[j], nums[k]});
++j;
--k;
while(j < k && nums[j] == nums[j-1]) ++j;
while(j < k && nums[k] == nums[k+1]) --k;
}
}
}
return ret;
}
};
$时间复杂度O(n),空间复杂度O();
方法:排序+双指针
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>>ret;
int i, j, l, k;
int n = nums.size();
if(n < 4) {
return ret;
}
sort(nums.begin(), nums.end());
long long sum4 = (long long)nums[0] + nums[1] + nums[2] + nums[3];
long long max3 = (long long)nums[n-1] + nums[n-2] + nums[n-3];
long long sum3 = 0;
long long max2 = (long long)nums[n-1] + nums[n-2];
for(i = 0; i < n - 3; ++i) {
if(sum4 > target) {
break;
}
if(i+4 < n) {
sum4 = sum4 - nums[i] + nums[i+4];
}
if(i > 0 && nums[i] == nums[i-1]) {
continue;
}
if(max3 + nums[i] < target) {
continue;
}
sum3 = (long long)nums[i] + nums[i+1] + nums[i+2] + nums[i+3];
for(j = i + 1; j < n - 2; ++j) {
if(sum3 > target) {
break;
}
if(j+3 < n) {
sum3 = sum3;
}
if(j > i + 1 && nums[j] == nums[j-1]) {
continue;
}
long long val = (long long)target - nums[i] - nums[j];
if(max2 < val) {
continue;
}
int l = j + 1;
int k = n - 1;
while(l < k) {
long long sum = nums[l] + nums[k];
if(sum > val) {
--k;
}else if(sum < val) {
++l;
}else {
ret.push_back({nums[i], nums[j], nums[l], nums[k]});
--k;
++l;
while(l < k && nums[k] == nums[k+1]) --k;
while(l < k && nums[l] == nums[l-1]) ++l;
}
}
}
}
ret.shrink_to_fit();
return ret;
}
};
$时间复杂度O(),空间复杂度O(
);