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 ...
随机推荐
- 如何上传本地项目到github
github作为git的代码托管,而许多大神都在上面托管自己的开源项目.现在,我来记录一下我是如何将本地项目上传到github上. 一.安装git工具(具体方法见百度) 二.配置全局 三.创建.ssh ...
- set_union和set_intersection
set_union使用方法: set_union(集合A起始地址,集合A终止地址,集合B起始地址,集合B终止地址,插入C集合中(操作:inserter(C.C.begin()))); set_inte ...
- MyBatis sql语句使用总结
MyBatis中Like语句使用总结 oracle数据库: SELECT * FROM user WHERE name like CONCAT('%',#{name},'%') 或 : SELECT ...
- Linux命令速查手册
Others make 通过外部编译器的,比如linux中的gcc集来编译源码 获取Makefile文件的命令触发编译 curl -X GET/POST -I 获取head curl有cache 查看 ...
- 【shell编程】之基础知识-函数
linux shell 可以用户定义函数,然后在shell脚本中可以随便调用. shell中函数的定义格式如下: [ function ] funname [()] { action; [return ...
- 【spring源码分析】BeanDefinitionRegistryPostProcessor解析
一.自定义BeanDefinitionRegistryPostProcessor BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProces ...
- 小D课堂【SpringBoot】接口Http协议开发实战
---恢复内容开始--- ====================2.SpringBoot接口Http协议开发实战 ============================= 1.SpringBoot ...
- uwsgi 报MemoryError
网站部署后,基本一天有时候几个小时就会502,查看uwsgi日志看到,一直在报MemoryError的错 之前以为是python版本的问题,说是32位的python最多支持2G,但查看了python版 ...
- 迭代器和增强型for循环
★迭代器: Java集合框架的集合类,我们有时候称之为容器.容器的种类有很多种,比如ArrayList.LinkedList.HashSet...,每种容器都有自己的特点,ArrayList底层维护的 ...
- What's New In Zeebe: Scaling Zeebe, New Client APIs, Faster Requests, Timestamps, NodeJS Client, and Default Topic is Back!
Written by Daniel Meyer on May 16 2018 in the What's New In Zeebe category. Welcome to the first-eve ...