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 ...
随机推荐
- let,const,var三者之间的区别
在ES6中新增了两种定义变量的命令let和const,在这之前相信大家都对var定义变量很熟悉,那么在了解ES6方法前, 1.我们先来回顾一下var定义变量的方法. 下面来看这段代码: for (va ...
- sql多表关联
inner join(等值连接) 只返回两个表中联结字段相等的行 left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录 right join(右联接) 返回包括右表中的所有 ...
- Windows平台上使用ANT编译Hadoop Eclipse Plugin
一.准备工作: 1.安装JDK 下载页面:http://www.oracle.com/technetwork/java/javase/downloads/index.html JDK6,JDK7都 ...
- vue2 阻止时间冒泡
click.stop.prevent <div class="content-right" @click.stop.prevent="pay" > ...
- 【技术累积】【点】【java】【8】maven常用命令(持续更新)
建立 mvn archetype:generate -DgroupId=com.andy.test -DartifactId=test-project -Dversion=0.0.1-SNAPSHOT ...
- ios 编译版本 最低版本 运行版本 动态链接库
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) 运行环境判断: #if __IPHONE_OS_VERSION_ ...
- WIN7无法保存打印机设置错误0x000006d9处理办法(转载)
办公电脑安装了GHOST版WIN7操作系统,在设置打印机共享时,报(错误0x000006d9),无法设置打印机共享, 查看微软官方文档:说是停止或禁用了Windows防火墙服务,必须启用 Window ...
- 路飞学城Python-Day180
部署作业 [pythonanywhere]
- js将timestamp对象与时间字符串之间的转换
1. 时间戳转日期字符串 var timestamp = timestampObj.time;获取时间戳的毫秒数 var d = new Date(timestamp); //根据时间戳生成的时间对象 ...
- Java多线程中Sleep与Wait的区别
Java中的多线程是一种抢占式的机制 而不是分时机制.抢占式机制指的是有多个线程处于可运行状态,但是只有一个线程在运行. 共同点: 1. 他们都是在多线程的环境下,都可以在程序的调用处阻塞指定的毫秒数 ...