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 ...
随机推荐
- url的使用
1.urls.py 默认是在主目录中,主路由配置文件,会包含最基本的地址映射,并且每个地址访问都必须要先经过该文件. 作用:通过 urls中定义好的地址找到对应的视图处理函数 urlpatterns ...
- Bagging-Adaboost-RF的粗糙理解
三种方法都是组合方法,组合方法是使用多个分类器进行投票[构造每个分类器的样本都是通过有放回抽样得到的] 1.Bagging(装袋):k次抽样,训练k次,得到k个模型(分类器),等权重投票 2.Adab ...
- 关于Adaboost——样本抽样的权值的实际意义
看这篇文章的前提:已经看了PRML中的Adaboost的算法流程 看懂下面的内容必须牢牢记住:Adaboost使用的误差函数是指数误差 文章主要目的:理解样本抽样的权值是为什么那样变化的. 得出的结论 ...
- mask-code-python
tf.sqeeze: 给定张量输入,此操作返回相同类型的张量,并删除所有尺寸为1的尺寸. 如果不想删除所有尺寸1尺寸,可以通过指定squeeze_dims来删除特定尺寸1尺寸.如果不想删除所有大小是1 ...
- 实验吧—密码学——WP之 杯酒人生
首先我们研究题目 1.这是古典密码 2.喵星人要发送一段密码 3.加密过的秘钥“HTRUZYJW” 4.秘钥加密前是一个单词 我们先解决这个秘钥,用凯撒解密 而我们知道,在古典密码里,有秘钥的加密方式 ...
- 《DSP using MATLAB》Problem 6.21
代码: %% ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ %% Output In ...
- 重写&重载
重写:子类对父类或接口中方法重新定义,是同一个方法 (1)子类不能重写final方法 (2)子类必须重写abstract方法 重载:一个类内部,方法同名,参数列表不同 (1)返回值不能作为区分重载方法 ...
- struts2的国际化i18n
先来例子,普通的读取配置文件中不同语言信息,一个测试类,一份中文配置文件,一份英文配置文件 中文配置文件,书写中文“欢迎”,myelipse自动转码 public class Readi18n { p ...
- Go Example--函数
package main import ( "fmt" ) func main() { res := plus(1,2) fmt.Println("1+2=", ...
- 【BZOJ1067】【SCOI2007】降雨量
新人求助,降雨量那题,本机AC提交AC 原题: 我们常常会说这样的话:“X年是自Y年以来降雨量最多的”.它的含义是X年的降雨量不超过Y年,且对于任意Y<Z<X,Z年的降雨量严格小于X年.例 ...