LeetCode——1. Two Sum
一.题目链接: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的更多相关文章
- 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 ...
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- [leetCode][013] Two Sum 2
题目: Given an array of integers that is already sorted in ascending order, find two numbers such that ...
- [LeetCode] #167# Two Sum II : 数组/二分查找/双指针
一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...
- [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针
一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...
- [array] leetcode - 40. Combination Sum II - Medium
leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...
- [array] leetcode - 39. Combination Sum - Medium
leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...
- LeetCode one Two Sum
LeetCode one Two Sum (JAVA) 简介:给定一个数组和目标值,寻找数组中符合求和条件的两个数. 问题详解: 给定一个数据类型为int的数组,一个数据类型为int的目标值targe ...
- [leetcode]40. Combination Sum II组合之和之二
Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...
- [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 ...
随机推荐
- scrapt中的数据提取,采用js2xml库
这个一个爬去美团的例子,应为数据都是在script中,小心封ip,尽量少运行. 先导入库几个库 import requests from bs4 import BeautifulSoup from l ...
- [LeetCode&Python] Problem 788. Rotated Digits
X is a good number if after rotating each digit individually by 180 degrees, we get a valid number t ...
- c日志宏
仅供参考,不推荐 #ifdef _DEBUG #define LOGDEBUG(format, ...)\ {\ FILE *fp = fopen("nccli.log", &qu ...
- 20155219实验三 敏捷开发与XP实践
实验内容 XP基础 XP核心实践 相关工具 敏捷开发与XP 1.敏捷开发(Agile Development)是一种以人为核心.迭代.循序渐进的开发方法."敏捷流程"是一系列价值观 ...
- webpack的一些详细配置
http://blog.csdn.net/c_kite/article/details/71279853
- IIS下使用 HTTP/2
IIS 使用 HTTP/2 什么叫HTTP/2? HTTP 2.0即超文本传输协议 2.0,是下一代HTTP协议.是由互联网工程任务组(IETF)的Hypertext Transfer Protoco ...
- (25)Django中操作cookie与session组件(添加cookie和删除cookie)
cookie是存在于客户端浏览器上的键值对,是明文的 cookie是当用户访问网站时候和数据提起携带过去,安全性比较差, 容易被拦截 session存在于服务端的键值对,是一串加密的字符串 当用户登陆 ...
- vue的指令绑定、事件、冒泡
a标签的属性绑定: v-once:就是第一次渲染什么就是什么,不会随着其他改变而改变,简言之就是绑定他不让他的值改变 防止跨站脚本攻击 如果你觉得安全的话,可以不要让变量的值显示成字符串 解决方法是: ...
- vue全家桶+Koa2开发笔记(3)--mongodb
1. 安装 momgodb brew install mongodb安装成功后执行 which mongod启动:mongod 2. 下载可视化操作数据库的软件 https://robomongo.o ...
- <--------------------------Java多态如何使用------------------------------>
11多态调用的三种格式 * A:多态的定义格式: * 就是父类的引用变量指向子类对象 父类类型 变量名 = new 子类类型(); 变量名.方法名(); * B: 普通类多态定义的格式 父类 变量名 ...