Problem describe:https://leetcode.com/problems/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.

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

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

AC code :

1.Bruth Algorithm

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
for(int i = ;i < nums.size();i++)
for(int j = i + ;j < nums.size();j++)
if(nums[i]+nums[j]==target)
{
res.push_back(i);
res.push_back(j);
}
return res; }
};

2.Hashmap

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int,int> map;
for(int i = ; i < nums.size();i++)
{
map[nums[i]] = i;
}
for(int i = ;i < nums.size();i++)
{
int left = target - nums[i];
if(map.count(left) && i < map[left])
{
res.push_back(i);
res.push_back(map[left]);
}
}
return res;
}
};

最新文章

  1. 解决谷歌浏览器中的input背景色默认是黄色
  2. Eclipse快捷键大全(转载)
  3. spring-mvc.xml中的配置
  4. jquery的$.extend和$.fn.extend作用及区别
  5. 转帖:使用TortoiseGit处理代码冲突
  6. 炼数成金hadoop视频干货04
  7. 最牛X的编码套路
  8. web标准(复习)--7 横向导航菜单
  9. GO语言基础
  10. ubuntu 安装输入法(fcitx)
  11. inflate的使用注意事项
  12. egret GUI 文本混排+文本链接的聊天解决方案【取巧法】
  13. Oracle ORA-39726压缩表删除字段处理方法
  14. JDBC02 利用JDBC连接数据库【使用数据库连接池】
  15. 浅谈js中null和undefined的区别
  16. android SDK与ADT版本更新问题
  17. Rosserial实现Windows-ROS交互操作
  18. mysql实现IP与整形互转
  19. iOS 第三方框架-MBProgressHUD
  20. Linux内存管理和应用

热门文章

  1. 【C#】获取任意文件的缩略图
  2. WPF媒体资源和图片资源寻址方式的杂谈
  3. WPF后台生成datatemplate(TreeViewItem例子)
  4. iOS判断当前时间是否处于某个时间段内
  5. SqlServer &amp; Windows 可更新订阅立即更新启用分布式事务协调器(MSDTC)
  6. 微信小程序把玩(三)tabBar底部导航
  7. MongoDB.Driver 管道 Aggregate
  8. 一份React-Native学习指南
  9. mingw(gcc)默认使用的是dwarf格式
  10. Redis EXISTS命令耗时过长case排查