一.题目链接:https://leetcode.com/articles/two-sum/

二.题目大意:

  给定一个int型数组A和int值a,要求从A中找到两个数,使得这两个数值的和为a;返回结果为一个数组,该数组存储的为这两个数在数组A中的下标。(题目假设结果是唯一的)

三.题解

  1.该题目首先最容易想到的就是暴力破解,只需要两个循环分别遍历数组;这样的话,时间复杂度为O(N2),空间复杂度为O(1),代码如下:

  

int* twoSum(int* nums, int numsSize, int target) {
int *rs = malloc(sizeof(int)*2);
int i = 0,j = 0;
for(i = 0; i < numsSize; i++)
for (j = i + 1; j < numsSize; j++)
{
if(nums[i] + nums[j] == target)
{
rs[0] = i;
rs[1] = j;
return rs;
}
}
return rs;
}

  2.由于O(N2)的时间复杂度效率太低,有没有更好的方法?我们只需想方设法优化第二个for循环即可(第一个for循环一般无法优化,因为该程序至少要遍历一次);可以考虑利用map来进行查询,代码如下:

  

 vector<int> twoSum(vector<int>& nums, int target) {
vector<int>rs;
int i = 0;
int temp;
map<int,int>hs;
map<int, int>::iterator iter;//由于map调用find()方法时,返回的结果为一个迭代器
for(i = 0; i < nums.size(); i++)
{ temp = target - nums[i];
iter = hs.find(temp);
if(iter != hs.end())
{
rs.push_back(iter->second);//iter->first和iter->second分别表示key和value
rs.push_back(i);
return rs;
}
hs.insert(pair<int,int>(nums[i],i));
}
return rs;
}

     由于map的查找时间为O(logN),故整个程序的时间复杂度为O(N*logN);空间复杂度为O(N)(因为程序额外利用的存储空间最大为N-1级别,即map的大小),实质上是以空间换取时间的一种策略,方法2和方法1相比,只是第二步查询的方式变了,这种思想值得借鉴。

  3.鉴于方法2的思想,我们还可以进一步去优化,那就是利用哈希表,c11标准中的哈希表为unordered_map,代码如下:

  

vector<int> twoSum(vector<int>& nums, int target) {
vector<int>rs;
int i = 0;
int temp;
unordered_map<int,int>hs;
unordered_map<int, int>::iterator iter;
for(i = 0; i < nums.size(); i++)
{ temp = target - nums[i];
iter = hs.find(temp);
if(iter != hs.end())
{
rs.push_back(iter->second);
rs.push_back(i);
return rs;
}
hs.insert(pair<int,int>(nums[i],i));
}
return rs;
}

  与方法2,唯一不同之处在于map换成了unordered_map,unordered_map查询时间为O(1),故整个程序的时间复杂度为O(N),空间复杂度为O(N)(与法2类似),只不过底层实现上与map有区别)。

注意:

1.map的底层实现是红黑树,所以保证了一个稳定的动态操作时间,查询、插入、删除都是O(logN),最坏和平均都是查询效率为O(logN);unordered_map底层的实现是哈希表,查询效率为O(1),虽然是O(1),但是并不是unordered_map查询时间一定比map短,因为实际情况中还要考虑到数据量,而且unordered_map的hash函数的构造速度也没那么快,所以不能一概而论,应该具体情况具体分析。而且unordered_map是C11标准中新加的,所以编译器必须支持c11标准才能用unordered_map。

2.在unordered_map之前,一般用hash_map,但是hash_map并没有被并入c++标准库中,所以有的编译器可能不支持,leetcode就不支持。。。;所以以后就用unordered_map代替hash_map。

    

LeetCode——1. Two Sum的更多相关文章

  1. Java for LeetCode 216 Combination Sum III

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  2. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  3. [leetCode][013] Two Sum 2

    题目: Given an array of integers that is already sorted in ascending order, find two numbers such that ...

  4. [LeetCode] #167# Two Sum II : 数组/二分查找/双指针

    一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...

  5. [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针

    一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...

  6. [array] leetcode - 40. Combination Sum II - Medium

    leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...

  7. [array] leetcode - 39. Combination Sum - Medium

    leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...

  8. LeetCode one Two Sum

    LeetCode one Two Sum (JAVA) 简介:给定一个数组和目标值,寻找数组中符合求和条件的两个数. 问题详解: 给定一个数据类型为int的数组,一个数据类型为int的目标值targe ...

  9. [leetcode]40. Combination Sum II组合之和之二

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...

  10. [LeetCode] 437. Path Sum III_ Easy tag: DFS

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

随机推荐

  1. Angular 组件

    1 2 change是TimepickerDemoCtrl上的,mytime在timepicker内部改变生效就会触发 3 timepicker内部绑定TimepickerDemoCtrl对值的监控 ...

  2. 纯C:url base64

    纯代码,来自互联网 base64.h #ifndef __BASE64_H__ #define __BASE64_H__ #ifdef __cplusplus extern "C" ...

  3. Gym102040 .Asia Dhaka Regional Contest(寒假自训第9场)

    B .Counting Inversion 题意:给定L,R,求这个区间的逆序对数之和.(L,R<1e15) 思路:一看这个范围就知道是数位DP. 只是维护的东西稍微多一点,需要记录后面的各种数 ...

  4. ubuntu软件管理

    https://www.cnblogs.com/forward/archive/2012/01/10/2318483.html 一.Ubuntu中软件安装方法1.APT方式(联网安装, 需要联网下载软 ...

  5. 2017-2018-2 20165313实验二《Java面向对象程序设计》

    实验报告封面 实验内容及步骤 实验一 1.试验要求: 参考 (http://www.cnblogs.com/rocedu/p/6371315.html#SECUNITTEST) 完成单元测试的学习. ...

  6. org.apache.commons.lang3.StringUtils中的StringUtils常用方法

    https://my.oschina.net/funmo/blog/615202?p=1 public static void TestStr(){ //null 和 ""操作~~ ...

  7. Redis源码剖析--列表t_list实现

    Redis中的列表对象比较特殊,在版本3.2之前,列表底层的编码是 ziplist 和 linkedlist 实现的, 但是在版本3.2之后,重新引入了一个 quicklist 的数据结构,列表的底层 ...

  8. oracle数据库丢失数据文件、控制文件、重做日志文件、初始化文件恢复方法

    rman  target/ list backup; 查看是否已备份,如果没有,那就不知道了 模拟故障,删除/u01/app/oracle/oradata/ORCL文件夹下的所有文件 sqlplus ...

  9. MySQL Replication--复制异常1

    ============================================== 问题描述: 1.从库环境:MySQL 5.7.19,主从都开启GTID模式 2.MySQL数据目录所有者被 ...

  10. What happens to our code? JavaScript 代码是怎样执行的

    1. 我们的代码第一步会被parser 语法分析程序分析. 如果没有报错之后 2. 生产SyntaxTree, 我们的代码会转换成machine code 3. 最终 我们的代码会被运行出来. 下面的 ...