Ai
1 Star 0 Fork 0

徐长贺/Leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
_1.cpp 1011 Bytes
一键复制 编辑 原始数据 按行查看 历史
Fisher Coder 提交于 2019-03-23 23:22 +08:00 . add #include statements
/**
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
*/
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;
vector<int> result;
for(int i = 0; i < nums.size(); i++){
// not found the second one
if (m.find(nums[i]) == m.end() ) {
// store the first one poisition into the second one's key
m[target - nums[i]] = i;
} else {
// found the second one
result.push_back(m[nums[i]]);
result.push_back(i);
break;
}
}
return result;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/isulong/Leetcode.git
git@gitee.com:isulong/Leetcode.git
isulong
Leetcode
Leetcode
master

搜索帮助