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;
}

LeetCode之“散列表”:Two Sum && 3Sum && 3Sum Closest && 4Sum的更多相关文章

  1. LeetCode之“散列表”:Isomorphic Strings

    题目链接 题目要求: Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic i ...

  2. LeetCode之“散列表”:Contains Duplicate && Contains Duplicate II

     1. Contains Duplicate 题目链接 题目要求: Given an array of integers, find if the array contains any duplica ...

  3. LeetCode之“散列表”:Single Number

    题目链接 题目要求: Given an array of integers, every element appears twice except for one. Find that single ...

  4. LeetCode之“散列表”:Valid Sudoku

    题目链接 题目要求: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku boar ...

  5. LeetCode解题报告—— Container With Most Water & 3Sum Closest & Letter Combinations of a Phone Number

    1.  Container With Most Water Given n non-negative integers a1, a2, ..., an, where each represents a ...

  6. LeetCode:3Sum, 3Sum Closest, 4Sum

    3Sum Closest Given an array S of n integers, find three integers in S such that the sum is closest t ...

  7. LeetCode 339. Nested List Weight Sum (嵌套列表重和)$

    Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...

  8. Leetcode 两数之和 (散列表)

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 15], target ...

  9. [leetcode]364. Nested List Weight Sum II嵌套列表加权和II

    Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...

随机推荐

  1. Django extra 和 annotate

    >>> qs=Question.objects.extra(select={'anum': 'SELECT COUNT(*) FROM questions_answer WHERE ...

  2. Dynamics CRM2016 Web API之Use custom FetchXML

    CRM2016中新增的web api支持fetch xml了,之前使用FetchXML的场景是在后天代码中通过组织服务的retrieve multiple方法,但实际的应用效果有多大,还需要在实际的项 ...

  3. 剑指Offer——搜狐畅游笔试题+知识点总结

    剑指Offer--搜狐畅游笔试题+知识点总结 情景回顾 时间:2016.9.24 10:00-12:00 地点:山东省网络环境智能计算技术重点实验室 事件:搜狐畅游笔试   注意事项:要有大局观,该舍 ...

  4. 与markdown的第一次接触

    什么是markdown markdown是一种比html轻量级的标记语言. markdown的介绍与学习请参考:markdown认识与入门 CSDN Markdown博客视频教程 知乎: 怎样引导新手 ...

  5. 使用github搭建网站

    http://blog.csdn.net/pipisorry/article/details/51707366 使用github建站 github设计了Pages功能,允许用户自定义项目首页,用来替代 ...

  6. Android核心安全机制(一)

    Android六种核心安全机制-加密.密钥.签名与证书 对于移动开发,程序猿很容易会忘记一些安全问题,如一个MD5的加密,大部分人都知道怎么去使用,但是其中的一些加密原理,加密方式却只有少部分会去了解 ...

  7. TraceView性能分析工具介绍

    一.TraceView简介 TraceView是AndroidSDK里面自带的工具,用于对Android的应用程序以及Framework层的代码进行性能分析. TraceView是图形化的工具,最终它 ...

  8. SSH深度历险(四) Maven初步学习

    这几天接触这个词,很多遍了,只是浅显的体会到它在GXPT中的好处,功能之强大,又通过网络查询了资料进一步的认识学习了,和大家分享. Maven是基于项目对象模型(POM),可以通过一小段描述信息来管理 ...

  9. 【一天一道LeetCode】#137. Single Number II

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  10. 看人装X,我就来气,开启极限装X模式

    本文书写,纯属扯淡,请勿观看 4进制比二进制更合理,在01的状态中添加了两种状态,从无到有和从有到无的两种过度状态. 如果非要用数值表示,用概率表示.01作为近代计算机的基础,但终究淘汰,构成下一代计 ...