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

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

2Sum

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

bool compare(const pair
&a, const pair
&b) { return a.first < b.first;}class Solution {public: vector
twoSum(vector
&numbers, int target) { return twoSum_2(numbers, target); } // solution 1: sort and select O(nlgn) vector
twoSum_1(vector
&numbers, int target) { // pair
vector
> nums(numbers.size()); for (int i = 0; i < numbers.size(); ++i) nums[i] = make_pair(numbers[i], i+1); sort(nums.begin(), nums.end(), compare); int l = 0, r = nums.size() - 1; while (l < r) { int sum = nums[l].first + nums[r].first; if (sum == target) break; else if (sum < target) l++; else r--; } vector
res; res.push_back(min(nums[l].second, nums[r].second)); res.push_back(max(nums[l].second, nums[r].second)); return res; } // solution 2: hashtable O(n) vector
twoSum_2(vector
&numbers, int target) { // exist bug; hash-table unordered_map
map; for (int i = 0; i < numbers.size(); ++i) map[numbers[i]] = i + 1; for (int i = 0; i < numbers.size(); ++i) { unordered_map
::iterator it = map.find(target - numbers[i]); if (it == map.end() || i+1 == it->second) continue; vector
res; res.push_back(min(i+1, it->second)); res.push_back(max(i+1, it->second)); return res; } }};

 

转载于:https://www.cnblogs.com/zhengjiankang/p/3595483.html

你可能感兴趣的文章
360°全景影像建库流程
查看>>
Java学习笔记51:数组转ArrayList和ArrayList转数组技巧
查看>>
atomsphere scattering
查看>>
数组和矩阵(3)——Next Greater Element I
查看>>
VS2019/VS2017安装源离线下载,更新,清理,企业版与论坛版重复下载
查看>>
多态的弊端
查看>>
Linux 文件基本属性: chown修改所属组 和 chmod修改文件属性命令
查看>>
python socket
查看>>
USACO Breed Proximity
查看>>
css装饰文本框input
查看>>
HBase RegionServer宕机处理恢复
查看>>
377. Combination Sum IV
查看>>
一款jq的计时器
查看>>
求1+2+…+n
查看>>
开发者必备的6款源码搜索引擎
查看>>
一个值只有0和1的字段,到底要不要建索引?
查看>>
JavaScript的Math对象
查看>>
form 禁止跳转
查看>>
第七周学习总结
查看>>
20145122《JAVA开发环境的熟悉》实验报告
查看>>