Computer Science/C++
[C++ Reminder] LeetCode 1. Two Sum
focalpoint
2023. 1. 23. 06:57
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int, int> hash;
for (int i = 0; i < nums.size(); i++) {
int num = target - nums[i];
// found
if (hash.find(num) != hash.end()) {
res.push_back(hash[num]);
res.push_back(i);
return res;
}
hash[nums[i]] = i;
}
return res;
}
};
int main() {
vector<int> vec{ 2, 7, 11, 15 };
Solution().twoSum(vec, 9);
return 0;
}