728x90
반응형
https://leetcode.com/problems/two-sum
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for(int i = 0 ;i<nums.size();i++)
{
for(int j = i+1;j<nums.size();j++)
{
if(nums[i]+nums[j] == target)
{
result.push_back(i);
result.push_back(j);
goto EXIT;
}
}
}
EXIT:
return result;
}
};
두번째 답
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
map<int,int> m;
for(int i = 0 ;i<nums.size();i++)
{
m[nums[i]] = i;
}
for(int i = 0 ;i<nums.size();i++)
{
int diff = target- nums[i];
if(m.find(diff)!=m.end())
{
if(m[diff] != i)
{
result.push_back(m[diff]);
result.push_back(i);
break;
}
}
}
return result;
}
};
728x90
반응형
'개발 > 코딩' 카테고리의 다른 글
해커랭크(HackerRank) - The Grid Search // C++ (0) | 2021.05.16 |
---|---|
[hackerrank] Minimum Absolute Difference in an Array / C++ (0) | 2020.12.07 |
해커랭크(HackerRank) - Closest Numbers / C++ (0) | 2020.07.11 |
해커랭크(HackerRank) - The Full Counting Sort / C++ (0) | 2020.07.11 |
해커랭크(HackerRank) - Counting Sort 1,2 / C++ (0) | 2020.07.11 |
댓글