๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

IN DEPTH CAKE/Supercoder

[c++/LeetCode-Hash Table] 1. Two Sum

 

 

 

 

๋‚œ์ด๋„Easy

ํ‚ค์›Œ๋“œ: Stack

 

 

๋ฌธ์ œ

 

์ •์ˆ˜ ๋ฐฐ์—ด nums์™€ ์ •์ˆ˜ target์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ๋‘ ์ˆซ์ž์˜ ํ•ฉ์ด target์ด ๋˜๋„๋กํ•˜๋Š” ์ˆซ์ž์˜ ์ธ๋ฑ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
๊ฐ ์ž…๋ ฅ์—๋Š” ์ •ํ™•ํžˆ ํ•˜๋‚˜์˜ ํ•ด๊ฒฐ์ฑ…์ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๋™์ผํ•œ ์š”์†Œ๋ฅผ ๋‘ ๋ฒˆ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.
์–ด๋–ค ์ˆœ์„œ๋กœ๋“  ๋‹ต์„ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

๋ฌธ์ œ ์›๋ฌธ: https://leetcode.com/problems/two-sum/description/

 

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

 

๋ฌธ์ œ ํ’€์ด

O(n) ์‹œ๊ฐ„ ์•ˆ์— ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด์„œ, array์˜ iteration์„ ๋„๋Š” ๋™์•ˆ ๋‹ต์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ’์„ ์กฐํšŒํ•  ์ˆ˜  ์žˆ๋„๋ก ํ•  ์ˆ˜ ์žˆ๋‹ค.

์ด๋ฅผ ์œ„ํ•ด์„œ Hash Table์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ํ˜„์žฌ ๊ฐ’๊ณผ์˜ ํ•ฉ์ด target์ด ๋˜๋Š” ๊ฐ’์„ ์ฐพ๋Š” ๊ฒƒ์ด ๋ชฉํ‘œ์ด๊ธฐ ๋•Œ๋ฌธ์— key ๊ฐ’์„ array ๊ฐ’์œผ๋กœ ํ•˜๊ณ , ํ˜„์žฌ ๊ฐ’์— ๋Œ€์‘๋˜๋Š”  key ๊ฐ’์ด hash ์— ์กด์žฌํ•˜๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ํ†ตํ•ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

#include <unordered_map>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        
        // key (int), value (int)
        unordered_map<int, int> hash;
        vector<int> ans;

        for(auto i=0; i < nums.size(); ++i){
            const auto ptr = hash.find(target - nums[i]);
            if(ptr != hash.end()){
                ans.emplace_back(i);
                ans.emplace_back(ptr -> second);
                return ans;
            }
            hash.insert({nums[i], i});
        }
        return ans;
    }
};

 

 

 

 

๋ฐ˜์‘ํ˜•