1. Two Sum[E]两数之和
题目
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] +nums [1] = 2 + 7 = 9,
return [0, 1]
思路
思路1:双重循环
这种是最容易想到的思路,比较暴躁,复杂度\(O(N^2)\)。
思路2:哈希表
题目对数a、b求和,但是返回的是等于target时a、b的下标,于是想到将数组下标与对应值作一个映射表。C++使用unordered_map关联容器可以实现键值与真值的映射。python中使用字典来实现类似功能。
Tips
unordered_map
1. 原型
template <class T, //键值类型
class T, // 映射类型
class hash = hash<key>, //哈希函数对象类型
class Pred = equal_to <key>, //相等比较函数对象类型
class Alloc = allocator < pair<cosnt key, T> > //alloctor类
>
2. 特性
- 关联性:通过key值检索value,而不是通过绝对地址(和顺序容器不同)
- 无序性:使用hash表存储,内部无序
- Map:每个值对应一个key值
- key唯一性:不存在两个元素的key一样
- 动态内存管理:使用动态内存管理模型来动态管理所需要的内存空间。
3. 常用函数
count
原型
size_type count (const key_type& k) const;
说明 :
使用给定的Key值计算元素。搜素容器中Key值作为输入参数k的元素,并返回元素的数量。由于unorder_map容器不允许存在重复的Key值,这说明如果容器中存在具有该Key值的元素,则该函数返回1,否则返回0。
4. 小结
unordered_map的数据以pair<const Key, T>保存,first是键值(key value),second是映射值(the mapped value)。赋值语句m[key value] = the mapped value。
C++
- 思路1
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> results;
for(int i=0;i<nums.size();i++)
{
for(int j=i+1;j<nums.size();j++)
{
if(nums[i]+nums[j]==target)
{
results.push_back(i);
results.push_back(j);
return results;
}
else
{
continue;
}
}
}
}
- 思路2
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> m;
vector<int> results;
//数组中的值作为map的键值,其下标作为对应的映射值
for(int i=0;i<nums.size();i++)
{
m[nums[i]] =i;
}
for(int i = 0;i<nums.size();i++)
{
int t = target - nums[i];
if(m.count(t) && m[t] != i) // 不能使用同样的数两次
{
results.push_back(i);
results.push_back(m[t]);
break;
}
}
return results;
}
Python
- 思路2
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#建立字典
table ={nums[i] : i for i in range(len(nums))}
results = []
for i in range(len(nums)):
t = target - nums[i]
if table.get(t) is not None and (table.get(t) != i):
results = [i, table.get(t)]
break;
return results
1. Two Sum[E]两数之和的更多相关文章
- Leetcode#1.Two Sum(两数之和)
题目描述 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 15], ta ...
- LeetCode OJ:Two Sum(两数之和)
Given an array of integers, find two numbers such that they add up to a specific target number. The ...
- LeetCode 1. Two Sum (两数之和)
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
- 力扣 —— Two Sum ( 两数之和) python实现
题目描述: 中文: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利 ...
- LeetCode 653. 两数之和 IV - 输入 BST(Two Sum IV - Input is a BST)
653. 两数之和 IV - 输入 BST 653. Two Sum IV - Input is a BST 题目描述 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定 ...
- LeetCode 170. Two Sum III - Data structure design (两数之和之三 - 数据结构设计)$
Design and implement a TwoSum class. It should support the following operations: add and find. add - ...
- LeetCode 371. Sum of Two Integers (两数之和)
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Exam ...
- [LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...
- 领扣-1/167 两数之和 Two Sum MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
随机推荐
- 8) 十分钟学会android--Activity的生命周期之停止与重启
恰当的停止与重启我们的activity是很重要的,在activity生命周期中,他们能确保用户感知到程序的存在并不会丢失他们的进度.在下面一些关键的场景中会涉及到停止与重启: 用户打开最近使用app的 ...
- linux+nginx+python+django环境配置
Django是一个开放源代码的Web应用框架,由Python写成,它最初是被开发来用于管理劳伦斯出版集团旗下的一些以新闻内容为主的网站的.python+django也是web开发者最受欢迎的框架.今天 ...
- 搞不懂的算法-排序篇<1>
最近在学习算法,跟着<Algorithms>这本书,可能是自己水平不够吧,看完排序算法后各种,希尔,归并,快排,堆的实现在脑子里乱成一锅粥,所以就打算大概总结一下,不求精确,全面,只想用平 ...
- ZBrush快捷键与鼠标操作
ZBrush是一款3D图形绘制软件,功能十分强大,且比较复杂,除了菜单栏功能按钮,ZBrush还提供了一系列快捷键与鼠标操作,熟练掌握ZBrush快捷键与鼠标操作,可以帮助您大大节省图形创作时间.下面 ...
- 数据库_数据分片与mycat服务
1.数据分片; 2.部署mycat服务;3.基于mycat服务创建新库新表. 一,数据分片 1.数据分片,也叫分库分表,即将存放在一台数据库服务器中的数据,按照特定方式进行拆分,分散存放到其它多台服务 ...
- 【udacity】机器学习-波士顿房价预测小结
Evernote Export 机器学习的运行步骤 1.导入数据 没什么注意的,成功导入数据集就可以了,打印看下数据的标准格式就行 用个info和describe 2.分析数据 这里要详细分析数据的内 ...
- 基于fullpage的自动播放,手动播放,暂停页面的功能
功能如下: 1.默认加载方式为“自动播放 ”方式,即从第1屏至第5屏 页面循环加载显示,每屏每次仅显示1个页面,页面间停留时间为“10”秒2.手动播放过程中,按数字键“1”-“5”,将直接切到指定页面 ...
- HDU1527 - 取石子游戏【威佐夫博弈】
有两堆石子,数量任意,可以不同.游戏开始由两个人轮流取石子.游戏规定,每次有两种不同的取法,一是可以在任意的一堆中取走任意多的石子:二是可以在两堆中同时取走相同数量的石子.最后把石子全部取完者为胜者. ...
- SQLAlchemy小知识点
1.创建数据库模型的时候增加添加上注释SQLAlchemy1.2新增了comment参数telephone = db.Column(db.String(11), nullable=False, com ...
- ROPI下载安装
ROPI下载安装 官方地址 参考文献 安装过程 wget http://num.math.uni-goettingen.de/~m.goerigk/ropi/0.1.0/ropi-0.1.0.tar. ...