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 ...
随机推荐
- javascript中标准事件流addEventListener介绍
addEventListener-开始 前面零散地写了些关于 addEventListener 的内容,觉得比较散,有些地方可能也说得不够清楚明白,所以决定以连载的形式从头到尾再写一篇. addEve ...
- Python 中文注释报错解决方法
代码中一旦有了中文注释便会报错. 原因 如果文件里有非ASCII字符,需要在第一行或第二行指定编码声明. 解决方法 在第一行或是第二行加入这么一句# -- coding: utf-8 -- 完美解决
- readonly and const variable
共同点:都是常量: 不同点:const的值必须在编译前确定,通常在声明的同时赋值:而readonly可在运行时确定:
- Java数组的运用
Java数组 应用1: 大乐透彩票模拟器: 规则: 前区01-35中随机生成5个号码 后区01-12中随机生成2个号码 模拟操作,系统自动生成号码组合,并且按从小到大的顺序输出结果 同时要求可以选择生 ...
- CorelDRAW X8超低价优惠啦,你却还在用CDR X4破解?!
最近大火的<都挺好> 已经完美收官 出于好奇,小编也正在追剧呢 同样出生在畸形的原生家庭 长大后 有钱就是苏明玉 没钱就是樊胜美 所以不要抱怨老天给了你怎样的资源 想要什么就要靠自己的双手 ...
- Java根据HttpServletRequest请求获取服务器的IP地址
以下总结了两种根据HttpServletRequest请求获取发出请求浏览器客户端所在服务器的IP地址方法: 代码: import javax.servlet.http.HttpServletRequ ...
- python类的内置attr属性
class Foo: x=1 def __init__(self,y): self.y=y def __getattr__(self, item): print('----> from geta ...
- 修改默认input(file)的样式
以上是默认的 <input type="file" > 但是丑爆了啊同志们~~长久以来都是调用大神的代码,今天我也小试牛刀,做出了如下效果: 这样还是能接受的样子啦~ ...
- linux 中配置假域名来测试
1.linux中配置假域名 找到hosts文件进行编辑 命令:vim /etc/hosts 配置: #centos(本机IP)192.168.1.179 www.imooc.com(假域名,自己设置) ...
- /etc/default/useradd文件内容及对应功能
1.GROUP=100 #依赖于/etc/login.defs的USE RGRUUPS_ENAB参数,如果为no,则在此处控制 2.HOME=/home #把用户的家路径健在/home中 3.INAC ...