Algorithm/LeetCode
1. Two Sum
유쾌한고등어
2022. 12. 22. 15:26
https://leetcode.com/problems/two-sum/description/
Two Sum - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
SOLUTION CODE
# PYTHON
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(0,len(nums)):
t = target - nums[i]
for j in range(i+1,len(nums)):
if t == nums[j]:
return [i,j]
# C++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m; //원소값, 인덱스 mapping
for(int i = 0; i < nums.size(); i++)
{
if(m.find(target-nums[i]) != m.end()) // 충족하는 수 존재하면
return {m[target-nums[i]], i}; // 인덱스 반환
m[nums[i]] = i;
}
}
};
● C++unordered hash map
-map_name.empty()
값이 비어 있으면 return 1, 비어있지않으면 return 0
-map_name.size()
-map_name[key] = value
-map_name.find(key)
키가 있으면 iterator, 키가없으면 map_name.end()
-count(key)
키에 해당하는 원소 개수 반환
키가 있으면 return 1,없으면 return 0
-insert({key,value})
맵에 pair<{key,value}> 추가하는 함수
-erase(key)
key에 해당하는 원소제거
-clear()
맵 초기화
● C++unordered hash map 실습
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main(){
unordered_map<string,int> um;
if(um.empty())
cout<< "unoredered_map은 비어있음"<<endl;
um.insert(make_pair("key1",1));
um["key2"] = 2;
um.insert({"key3",3});
cout<<"unoredered_map의 크기는 " << um.size() <<"입니다." <<endl;
// auto로 해도 됌
for(pair<string,int> elem : um){
cout<<"key : " << elem.first << "value : " << elem.second<< endl;
}
if(um.find("key2")!=um.end()){
um.erase("key2");
}
cout<<"unordered_map 의 크기는 "<<um.size()<<" 이다."<<endl;
for(auto elem : um){
cout<<"key : " <<elem.first <<" value : "<<elem.second<<endl;
}
return 0;
}