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 ...
随机推荐
- NSLayoutConstraint的使用
*一切皆代码*- -- #继承关系框架|类|类:-:|:-:|:-:UIKit|NSLayoutConstraint|--|-|- #应用场景UI界面的搭建一般会占用项目开发相当一部分的时间.涉及到控 ...
- 利用javascript(自定义事件)记录尺寸可变元素的尺寸变化过程
1.效果图 2.源码 <%@ page contentType="text/html;charset=UTF-8" language="java" %&g ...
- Android 消息队列机制
在非UI线程使用Handler进行线程通信时,一般都需要进行3个步骤: 创建Looper Looper.prepar() 创建Handler 启动消息循环Looper.loop() 通过这3步,基本就 ...
- R 连接DB2数据库,并制作词图
#写在前面的话:此教程主要是用R连接了DB2数据库,并进行文本分析,制作了词图 #教程为markdown编写 ---title: "网站留言分析"output: html_docu ...
- 使用JDK和axis2发布webservice
最近使用webservice进行远程调用一直很火,自从JDK1.6版本发布后,发布一个webservice项目变得更加简单了 笔者由于工作的需要针对JDK和axis2如何发布webservice做过相 ...
- HDL之Bitwise operation
1 Verilog 1.1 Bitwise operator Bitwise operators perform a bit wise operation on two operands. They ...
- swift 类型备份
Swift语法3.03(类型Types) https://www.jianshu.com/p/839f9bc4b9a3 https://developer.apple.com/library/cont ...
- 【数据分析学习】Pandas思维导图
点我查看原版
- express+node.js搭建的服务器和在sublimeServer下的页面请求报跨域错误
1.前端页面使用vue中的axios请求nodejs响应.报以下错误: Failed to load http://localhost:3000/users/validate: Response to ...
- 使用Ansible安装部署nginx+php+mysql之安装mysql(3)
三.使用Ansible安装mysql 1.mysq.yaml文件 - hosts: clong remote_user: root gather_facts: no tasks: # 安装rpm包 - ...