-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtwoSum.h
More file actions
35 lines (31 loc) · 913 Bytes
/
twoSum.h
File metadata and controls
35 lines (31 loc) · 913 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//
// twoSum.h
// array
//
// Created by junlongj on 2019/8/6.
// Copyright © 2019 junl. All rights reserved.
//
#ifndef twoSum_hpp
#define twoSum_hpp
#include <stdio.h>
#include <vector>
namespace leetcode {
/*
1.两数之和
思路:通过集合来保存之前遍历过的元素,这样每次查找的时候先判断target-当前值的元素在不在hash table里面,就可以计算出结果了.
*/
std::vector<int> twoSum(std::vector<int>& nums, int target) {
std::map<int,int> mm;//key为当前值,value为下标
std::vector<int> result;
for (int i=0;i<nums.size();i++){
if(mm.find(target-nums[i]) == mm.end()){
mm[nums[i]]=i;
}else{
result.push_back(mm[target-nums[i]]);
result.push_back(i);
}
}
return result;
}
}
#endif /* twoSum_hpp */