문제요약:
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<int, int> 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
'알고리즘 문제풀이' 카테고리의 다른 글
[알고리즘] LeetCode 202번 "Happy Number" (C/C++) - Don 임베디드 (0) | 2022.09.29 |
---|---|
[알고리즘] LeetCode 746번 "Min Cost Climbing Stairs" (C/C++) - Don 임베디드 (0) | 2022.09.28 |
[알고리즘] LeetCode 21번 "Merge Two Sorted Lists" (C/C++) - Don 임베디드 (0) | 2022.09.26 |
[알고리즘] LeetCode 543번 "Diameter of Binary Tree" (C/C++) - Don 임베디드 (0) | 2022.09.21 |
[알고리즘] 백준 7568번 "덩치" (C/C++) - Don 임베디드 (23) | 2022.04.22 |