博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode TwoSum
阅读量:4314 次
发布时间:2019-06-06

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

class Solution {public:    vector
twoSum(vector
&numbers, int target) { vector
ret; vector
> nums; for (int i=0; i
target) { j--; } else if (sum < target) { i++; } else { break; } } ret.push_back(nums[i].second); ret.push_back(nums[j].second); sort(ret.begin(), ret.end()); return ret; }};

怒刷存在感

第二轮:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

感觉第一次做的有点粗糙,看了一发答案简洁许多:

class Solution {public:    vector
twoSum(vector
&numbers, int target) { unordered_map
n2i; int len = numbers.size(); vector
res; for (int i=0; i
0) { res = {n2i[target-cur] + 1, i + 1}; return res; } n2i.insert({cur, i}); } return res; }};

 

转载于:https://www.cnblogs.com/lailailai/p/3615042.html

你可能感兴趣的文章
架构之美阅读笔记02
查看>>
Mac中安装Vim7.4
查看>>
VC++工程文件说明
查看>>
C#基础(string)
查看>>
JavaScript-06-Dom操作
查看>>
MYSQL变量
查看>>
8、颠倒任意一个字符串的X个字符(第一个和倒数第一个颠倒,第二个和倒数第二个颠倒 ... )...
查看>>
mysql之索引
查看>>
openlayers3设置zoom不变
查看>>
vector
查看>>
怎样花两年时间去面试一个人
查看>>
算法速成系列
查看>>
The Pilots Brothers' refrigerator(dfs)
查看>>
usb 编程知识 总结
查看>>
iOS-OC-基础-NSString常用方法
查看>>
python-字典(第二篇(四):字典)
查看>>
http 4中 cache 头
查看>>
类加载器-双亲委派模型
查看>>
HDU5649 DZY Loves Sorting 线段树
查看>>
Python学习---range/for/break/continue简单使用
查看>>