본문 바로가기

알고리즘 문제풀이

[알고리즘] LeetCode 1번 "Two Sum" (C/C++) - Don 임베디드

문제요약:

Given an array of integers nums and an integer target,

return indices of the two numbers such that they add up to target.

 

 

제약:

Each input would have exactly one solution.

You cannot use the same element twice.

Answer can be in any order.

 

예제 1 입력. 예제 1 출력.
nums = [2,7,11,15], target = 9 [0,1]
예제 2 입력. 예제 2 출력.
nums = [3,2,4], target = 6 [1,2]
예제 3 입력. 예제 3 출력.
nums = [3,3], target = 6 [0,1]

 

 

정답코드:

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
class Solution {
public:
    map<intint> myHashTable;
    
    vector<int> twoSum(vector<int>& nums, int target) {
        vector <int> vReturn;
        
        // check if the couple for i th element is in the hash table.
        for (int i = 0; i < nums.size(); i++)
        {
            int nCouple = target - nums.at(i); 
            if (myHashTable.find(nCouple) != myHashTable.end())
            {
                vReturn.push_back(i);
                vReturn.push_back(myHashTable.find(nCouple)->second);
                break;
            }
            else
            {
                myHashTable.insert(pair<int,int>(nums.at(i),i));
            }
        }
        
        return vReturn;
    }
};
cs

핵심 idea:

Hashing을 통한 O(N) Solution

 

원본 링크: https://leetcode.com/problems/two-sum/