새발블로그
[프로그래머스/C++] 수 조작하기 1 본문
문제
https://school.programmers.co.kr/learn/courses/30/lessons/181926
풀이방법
풀이 1
문제에서 요구하는 대로 함
풀이 2
STL map 사용
특정 문자에 대한 값이 변하지 않으니 맵을 사용해도 좋을 것 같아서 가져왔다.
MAP : 각 노드가 key 와 value 쌍으로 이루어진 트리로, 중복을 허용하지 않음
first와 second가 있는 pair 객체로 저장되면 first -key, second-value로 저장
c++ map의 내부 구현은 레드블랙트리라합니다.... O(logn)
map<key, value>
특징
- 자료를 저장할 때 내부에서 자동으로 key를 중심으로 오름차순
- 내림차순 : map<int, int, greater> map이름
사용방법
- 헤더 : #include<map>
- 맵 선언 : map<key type, value type> 이름
- map 에서 데이터를 찾을 땐 iterator 사용 (m.find("key")
- 못찾으면 m.end() 반환~~
- 삽입 : map.insert({"key", 300});
- 반복문 접근 : m.begin()~ m.end()
- 삭제 : map.erase(특정 위치 인덱스)
- 삭제(요소) : map.erase("key")
- 모든 요소 삭제 : map.drease(map.begin(), map.end()); / map.clear();
풀이1
#include <string>
#include <vector>
using namespace std;
int solution(int n, string control)
{
for (char c : control)
{
if (c =='w')
n+=1;
else if (c =='s')
n-=1;
else if (c =='d')
n+=10;
else if (c =='a')
n-=10;
}
int answer = n;
return answer;
}
풀이2 (다른 사람풀이)
#include <string>
#include <vector>
#include <map>
using namespace std;
map <char, int> m = {{'w', 1}, {'s', -1}, {'d', 10}, {'a', -10}};
int solution(int n, string control) {
int answer = n;
for(char ch : control)
answer += m[ch];
return answer;
}
'Problem Solving > Programmers' 카테고리의 다른 글
| [프로그래머스/C++] 수열과 구간 쿼리 (0) | 2024.03.07 |
|---|---|
| [프로그래머스/C++] 수 조작하기2 (0) | 2024.03.07 |
| [프로그래머스/C++] 주사위 게임 2 (0) | 2024.03.05 |
| [프로그래머스/C++] 두 수의 연산값 비교하기 (0) | 2024.03.04 |
| [프로그래머스/C++] 문자열 돌리기 (0) | 2024.03.04 |