Scribbling

[C++ Reminder] LeetCode 1. Two Sum 본문

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;
}

 

'Computer Science > C++' 카테고리의 다른 글

[C++] 49. Group Anagrams  (0) 2023.08.18
[C++] LeetCode 242. Valid Anagram  (0) 2023.08.18
[C++] LeetCode 217. Contains Duplicate  (0) 2023.08.18
[C++ Reminder] LeetCode: 15. 3Sum  (0) 2023.01.26
[C++ Reminder] LeetCode 2. Add Two Numbers  (0) 2023.01.23