类似的题目可以用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、

最新文章

  1. DLL库
  2. 删除win7远程桌面历史记录
  3. Redis发布订阅实现原理
  4. php的Excel相关操作
  5. html5网页动画总结--jQuery旋转插件jqueryrotate
  6. 在sap系统设置纸张打印格式(针式打印机)
  7. MFC中release版本和debug版本区别
  8. php的fread函数的一个巨大的坑
  9. SQL Server 的 3 种连接
  10. CentOS 漏洞修补
  11. js获取手机型号和手机操作系统版本号
  12. 《Linux下cp XXX1 XXX2的功能》的实现
  13. day 17 - 2 递归函数练习
  14. 大型分布式架构设计与实现-第一章SOA(面向服务的体系架构)
  15. python自动化系列
  16. eclipse git 拉取内容
  17. 【Redis】Redis cluster集群搭建
  18. [转]Bootstrap table 分页 In asp.net MVC
  19. 胜利大逃亡(杭电hdu1253)bfs简单题
  20. 使用rundll32.exe绕过应用程序白名单(多种方法)

热门文章

  1. VIM查找空格
  2. Alice&#39;s Classified Message HDU - 5558 后缀自动机求某个后缀出现的最早位置
  3. sublime里面几个个人觉得比较实用的快捷键
  4. python--面向对象:多态与封装
  5. nginx-rtmp-module 指令详解
  6. unlocked - 非锁定的标准输入输出函数
  7. NCM格式转换MP3格式
  8. linux常用命令-3文件与目录相关命令
  9. asp.net MVC项目,localhost响应时间过长
  10. activemq启动失败修改Linux服务器名称