题目


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]两数之和的更多相关文章

  1. Leetcode#1.Two Sum(两数之和)

    题目描述 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 15], ta ...

  2. LeetCode OJ:Two Sum(两数之和)

    Given an array of integers, find two numbers such that they add up to a specific target number. The ...

  3. LeetCode 1. Two Sum (两数之和)

    Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...

  4. 力扣 —— Two Sum ( 两数之和) python实现

    题目描述: 中文: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利 ...

  5. LeetCode 653. 两数之和 IV - 输入 BST(Two Sum IV - Input is a BST)

    653. 两数之和 IV - 输入 BST 653. Two Sum IV - Input is a BST 题目描述 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定 ...

  6. LeetCode 170. Two Sum III - Data structure design (两数之和之三 - 数据结构设计)$

    Design and implement a TwoSum class. It should support the following operations: add and find. add - ...

  7. 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 ...

  8. [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 ...

  9. 领扣-1/167 两数之和 Two Sum MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

随机推荐

  1. 云信 短信发送 demo

    package com.dataTaskListener; import org.apache.commons.httpclient.Header; import org.apache.commons ...

  2. call by value 和 call by reference 的区别

    引用自https://zhidao.baidu.com/question/340173099.html Call by Value就是传值的方式,函数调用时是把实参的值传给形参,函数调用结束后形参的值 ...

  3. Java数组操作工具

    原文地址:http://blog.csdn.net/qq446282412/article/details/8913690 2013-05-11 10:27   看到网上的一段关于对数组操作的代码,觉 ...

  4. 关于VS 2013连接Microsoft Access 2013的相关问题

      ①   下载安装Microsoft Access Database Engine 2010 Redistributable(28MB),共有32bit(下载)和64bit(下载)两个版本,具体要安 ...

  5. java加密解密算法位运算

    一.实例说明 本实例通过位运算的异或运算符 “ ^ ” 把字符串与一个指定的值进行异或运算,从而改变每个字符串中字符的值,这样就可以得到一个加密后的字符串.当把加密后的字符串作为程序输入内容,异或运算 ...

  6. UBuntu安裝使用PIP

    Windows下安裝python包還是比較方便的,直接在FLD網站下載對應的EXE文件就可以安裝,在linux系統下,使用pip,easy egg 管理工具可以減輕安裝負擔. 原文鏈接:http:// ...

  7. ES : 软件工程学的复杂度理论及物理学解释

    系统论里面总是有一些通用的专业术语 比如复杂度.熵.焓,复杂度专门独立出来,成为复杂度理论 文章摘抄于:<非线性动力学> 刘秉政 编著  5.5 复杂性及其测度 热力学的几个专业术语 熵. ...

  8. 路飞学城Python-Day117

    jango用户登录界面 """ Django settings for cnblog project. Generated by 'django-admin startp ...

  9. MySQL笔记5-----索引(覆盖索引等)

    1.概念: 覆盖索引:(个人理解)就是包含所有查询记录的索引.当查询量过大时可以采用覆盖索引来进行查询,效率较高. 回表:建立覆盖索引就是避免回表,回表效率会很慢. select查询的字段只有索引列, ...

  10. 【BZOJ3451】Tyvj1953 Normal - 点分治+FFT

    题目来源:NOI2019模拟测试赛(七) 非原题面,题意有略微区别 题意: 吐槽: 心态崩了. 好不容易场上想出一题正解,写了三个小时结果写了个假的点分治,卡成$O(n^2)$ 我退役吧. 题解: 原 ...