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. Eric5 for Python 3.3.3安装指南

    一言蔽之,搭配是关键.以32位Window为例,先后安装: 1.PyQt PyQt4-4.10.3-gpl-Py3.3-Qt4.8.5-x32.exe http://www.riverbankcomp ...

  2. [ExtJS5学习笔记]第三十六节 报表组件mzPivotGrid

    mzPivotGrid 是一个报表组件,采用这个组件之后,可以令你的应用体现更多的价值. 什么是pivot grid 什么是mzPivotGrid 学习资源 与图表组件的融合 什么是pivot gri ...

  3. [LaTex]插图

    1.不错的Latex参考网站 http://www.ctex.org/documents/latex/graphics/node120.html http://www.ctex.org/documen ...

  4. 分析MapReduce执行过程+统计单词数例子

    MapReduce 运行的时候,会通过 Mapper 运行的任务读取 HDFS 中的数据文件,然后调用自己的方法,处理数据,最后输出.Reducer 任务会接收 Mapper 任务输出的数据,作为自己 ...

  5. 6.4、Android Studio的GPU Monitor

    Android Monitor包含GPU Monitor,它将可视化的显示渲染窗体的时间.GPU Monitor可以帮助你: 1. 迅速查看UI窗体生成 2. 辨别是否渲染管道超出使用线程时间 在GP ...

  6. Cocos2D v3.4.9粒子效果不能显示的原因分析及解决办法

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 在游戏App中为了衬托气氛我们往往使用一些特殊的图形效果,粒子 ...

  7. 利用Camera和Matrix实现有趣的卡片效果

    这篇文章主要讲解一个翻转切换内容的卡片效果,主要利用Camera和Matrix来实现,主要是为了加深对Camera和Matrix的理解,如果对Camera和Matrix不清楚地童鞋可以看我的上篇文章: ...

  8. 【翻译】Ext JS 6.2 早期访问版本发布

    原文:Announcing Ext JS 6.2 Early Access 非常开心,Sencha Ext JS 6.2早期访问版本今天发布了.早期访问版本的主要目的是为了让大家进行测试并评估Ext ...

  9. linux 定时任务详解 按秒设定

    实现linux定时任务有:cron.anacron.at等,这里主要介绍cron服务. 名词解释: cron是服务名称,crond是后台进程,crontab则是定制好的计划任务表. 软件包安装: 要使 ...

  10. UNIX网络编程——使用select函数编写客户端和服务器

    首先看原先<UNIX网络编程--并发服务器(TCP)>的代码,服务器代码serv.c: #include<stdio.h> #include<sys/types.h> ...