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