Algo: Two Sum
类似的题目可以用HashTable的思想解决。
1、Two Sum
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, and you may not use the same element twice.
https://leetcode.com/problems/two-sum/description/
http://www.cnblogs.com/grandyang/p/4130379.html
https://blog.csdn.net/gatieme/article/details/50596965
https://segmentfault.com/a/1190000006697526
#include <vector>
#include <unordered_map> std::vector<int> twoSum(std::vector<int>& nums, int target)
{
int size = (int)nums.size(); std::unordered_map<int, int> mp;
std::vector<int> ans; for(int i = ; i < size; ++i)
{
if(mp.count(target - nums[i]))
{
ans.push_back(mp[target - nums[i]]);
ans.push_back(i); break;
} mp[nums[i]] = i;
} return ans;
}
2、Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
https://www.cnblogs.com/grandyang/p/5185815.html
#include <vector> std::vector<int> twoSum(std::vector<int>& numbers, int target)
{
int l = ;
int r = (int)numbers.size() - ; while (l < r)
{
int sum = numbers[l] + numbers[r];
if (sum == target)
{
return {l + , r + };
}
else if (sum < target)
{
++l;
}
else
{
--r;
}
} return {};
}
3、
最新文章
- DLL库
- 删除win7远程桌面历史记录
- Redis发布订阅实现原理
- php的Excel相关操作
- html5网页动画总结--jQuery旋转插件jqueryrotate
- 在sap系统设置纸张打印格式(针式打印机)
- MFC中release版本和debug版本区别
- php的fread函数的一个巨大的坑
- SQL Server 的 3 种连接
- CentOS 漏洞修补
- js获取手机型号和手机操作系统版本号
- 《Linux下cp XXX1 XXX2的功能》的实现
- day 17 - 2 递归函数练习
- 大型分布式架构设计与实现-第一章SOA(面向服务的体系架构)
- python自动化系列
- eclipse git 拉取内容
- 【Redis】Redis cluster集群搭建
- [转]Bootstrap table 分页 In asp.net MVC
- 胜利大逃亡(杭电hdu1253)bfs简单题
- 使用rundll32.exe绕过应用程序白名单(多种方法)