LeetCode之“散列表”:Two Sum && 3Sum && 3Sum Closest && 4Sum

时间:2023-12-18 18:13:20

  1. Two Sum 

  题目链接

  题目要求:

  Given an array of integers, find two numbers such that they add up to a specific target number.

  The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

  You may assume that each input would have exactly one solution.

  Input: numbers={2, 7, 11, 15}, target=9
  Output: index1=1, index2=2

  这道题如果使用Brute Force,在LeetCode上会超时,具体程序如下:

 vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ret;
int sz = nums.size();
for(int i = ; i < sz; i++)
for(int j = i + ; j < sz; j++)
{
if(nums[i] + nums[j] == target)
{
ret.push_back(i);
ret.push_back(j);
return ret;
}
} return ret;
}

  如果我们利用哈希表来实现,则时间复杂度能达到O(n),程序如下:

 vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ret;
unordered_map<int, int> hashMap;
int sz = nums.size();
for(int i = ; i < sz; i++)
{
int tmp = target - nums[i];
if(hashMap.find(tmp) != hashMap.end())
{
ret.push_back(hashMap[tmp] + );
ret.push_back(i + );
break;
}
else
hashMap[nums[i]] = i;
} return ret;
}

  在上述程序中我们使用了unordered_map这个数据结构,它要比map要快,因为它存贮和访问元素是根据元素的哈希值来进行的。在cplusplus.com上有比较了这两者在访问单个元素时的速度:

  unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.

 2. 3Sum

  题目链接

  题目要求:

  Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

  Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-    - -},
A solution set is:
(-, , )
(-, -, )

  该题解法参考自一博文。要解决该题,首先我们将数组排序,然后将其降维(即降为2维),最后再调用Two Sum算法。具体程序中,我们采用的是Two Pointers方法,具体程序如下:

 void twoSum(vector<int>& nums, int start, int target, vector<vector<int> >& ret) {
int head = start, tail = nums.size() - ;
while(head < tail)
{
int tmp = nums[head] + nums[tail];
if(tmp < target)
head++;
else if(tmp > target)
tail--;
else
{
ret.push_back({nums[start-], nums[head], nums[tail]}); // 去除重复
int k = head + ;
while(k < tail && nums[k] == nums[head])
k++;
head = k; // 去除重复
k = tail - ;
while(k > head && nums[k] == nums[tail])
k--;
tail = k;
}
}
} vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int> > ret;
sort(nums.begin(), nums.end()); int sz = nums.size();
for(int i = ; i < sz - ; i++)
{
// 去除重复
if(i > && nums[i] == nums[i - ])
continue; int target = - nums[i];
twoSum(nums, i + , target, ret);
} return ret;
}

  3. 3Sum Closest

  题目链接

  题目要求:

  Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-   -}, and target = .
The sum that is closest to the target is . (- + + = ).

  该题解法跟上题类似:

 void threeSumClosest(vector<int>& nums, int start, int target, int& cloSum) {
int head = start, tail = nums.size() - ;
while (head < tail)
{
int tmp = nums[start - ] + nums[head] + nums[tail];
if(tmp > target)
{
if(tmp - target < abs(cloSum - target))
cloSum = tmp;
tail--;
}
else if(tmp < target)
{
if(target - tmp < abs(target - cloSum))
cloSum = tmp;
head++;
}
else
{
cloSum = target;
return;
}
}
} int threeSumClosest(vector<int>& nums, int target) {
int cloSum = INT_MAX - ; // 减去10000,以防溢出
sort(nums.begin(), nums.end()); // 要充分利用已排序这个条件
int sz = nums.size();
for(int i = ; i < sz - ; i++)
{
// 去除重复
if(i > && nums[i] == nums[i-])
continue; threeSumClosest(nums, i + , target , cloSum);
} return cloSum;
}

  4. 4Sum

  题目链接

  题目要求:

  Given an array S of n integers, are there elements abc, 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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.
    For example, given array S = {  -  - }, and target = .
A solution set is:
(-, , , )
(-, -, , )
(-, , , )

  该题解法跟3Sum类似:

 void twoSum(vector<int>& nums, int start, int target, int first, int second, vector<vector<int>>& ret)
{
int head = start, tail = nums.size() - ;
while(head < tail)
{
int tmp = nums[head] + nums[tail];
if(tmp < target)
head++;
else if(tmp > target)
tail--;
else
{
ret.push_back({first, second, nums[head], nums[tail]}); // 去除重复
int k = head + ;
while(k < tail && nums[k] == nums[head])
k++;
head = k; // 去除重复
k = tail - ;
while(k > head && nums[k] == nums[tail])
k--;
tail = k;
}
}
} vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> ret;
sort(nums.begin(), nums.end());
int sz = nums.size();
for(int i = ; i < sz - ; i++)
{
// 去除重复
if(i > && nums[i] == nums[i-])
continue;
for(int j = i + ; j < sz - ; j++)
{
// 去除重复
if(j > i + && nums[j] == nums[j-])
continue;
twoSum(nums, j + , target - nums[i] - nums[j], nums[i], nums[j], ret);
}
} return ret;
}