博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode——1. Two Sum
阅读量:4137 次
发布时间:2019-05-25

本文共 1843 字,大约阅读时间需要 6 分钟。

题目

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

解答

用一个unordered_map的结构来存储numbers,其中key是nums中的元素,value是nums中该元素对应的下标。

由于unordered_map是基于hash表来实现的,所以其查找时间复杂度为O(1)。
但是先要存储,时间为O(N)。

hash.find(numberToFind) != hash.end()

如果成立,表明numberToFind是在hash里面。即找到了另外一个数字。

如果上面代码不成立,即numberToFind不在hash里面,所以需要加入。

经典代码:

**for (int i = 0; i < numbers.size(); i++) {        int numberToFind = target - numbers[i];            //if numberToFind is found in map, return them        if (hash.find(numberToFind) != hash.end()) {                    //+1 because indices are NOT zero based            result.push_back(hash[numberToFind] + 1);            result.push_back(i + 1);                        return result;        }            //number was not found. Put it in the map.        hash[numbers[i]] = i;**

整个代码

vector
twoSum(vector
&numbers, int target){ //Key is the number and value is its index in the vector. unordered_map
hash; vector
result; for (int i = 0; i < numbers.size(); i++) { int numberToFind = target - numbers[i]; //if numberToFind is found in map, return them if (hash.find(numberToFind) != hash.end()) { //+1 because indices are NOT zero based result.push_back(hash[numberToFind] + 1); result.push_back(i + 1); return result; } //number was not found. Put it in the map. hash[numbers[i]] = i; } return result;}

转载地址:http://aexvi.baihongyu.com/

你可能感兴趣的文章
动态库调动态库
查看>>
Kubernetes集群搭建之CNI-Flanneld部署篇
查看>>
k8s web终端连接工具
查看>>
手绘VS码绘(一):静态图绘制(码绘使用P5.js)
查看>>
手绘VS码绘(二):动态图绘制(码绘使用Processing)
查看>>
基于P5.js的“绘画系统”
查看>>
《达芬奇的人生密码》观后感
查看>>
论文翻译:《一个包容性设计的具体例子:聋人导向可访问性》
查看>>
基于“分形”编写的交互应用
查看>>
《融入动画技术的交互应用》主题博文推荐
查看>>
链睿和家乐福合作推出下一代零售业隐私保护技术
查看>>
Unifrax宣布新建SiFAB™生产线
查看>>
艾默生纪念谷轮™在空调和制冷领域的百年创新成就
查看>>
NEXO代币持有者获得20,428,359.89美元股息
查看>>
Piper Sandler为EverArc收购Perimeter Solutions提供咨询服务
查看>>
RMRK筹集600万美元,用于在Polkadot上建立先进的NFT系统标准
查看>>
JavaSE_day14 集合中的Map集合_键值映射关系
查看>>
异常 Java学习Day_15
查看>>
Mysql初始化的命令
查看>>
MySQL关键字的些许问题
查看>>