문제
풀이
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
vector<string> solution(vector<string> strings, int n) {
vector<string> answer;
multimap<char ,string> hash;
sort(strings.begin(), strings.end());
for(int i=0; i<strings.size(); i++) hash.insert(make_pair(strings[i][n],strings[i]));
for(auto i : hash) answer.push_back(i.second);
return answer;
}
key가 숫자가 아닌 char이어야 했기 때문에 map을 사용했고,
그중에도 중복을 허용하고 key를 오름차순으로 자동 정렬해주는 multimap을 사용했다.
map
-중복을 허용하지 않고, key를 기준으로 오름차순 자동 정렬된다.
multimap
-중복을 허용하고, key를 기준으로 오름차순 자동 정렬된다.
unordered_map
-중복을 허용하지 않고 정렬 없이 저장한다.
다른 사람 코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int i;
bool compare (string a, string b) {
return a[i] == b[i] ? a < b : a[i] < b[i];
}
vector<string> solution(vector<string> strings, int n) {
i = n;
sort (strings.begin(), strings.end(), compare);
return strings;
}
sort를 이용하여 단 몇 줄만으로 문제를 해결했다!
sort() 3번째 인자
정렬을 어떤 식으로 할 것인지 알려주는 함수
함수는 반환 타입이 bool타입이어야 하며, 매개변수는 두 개여야 하고 두 매개변수의 타입은 정렬할 데이터의 타입과 일치해야 한다.
[c++ STL] Multimap 기본 사용법 및 예제
Multimap은 map이지만 같은 key값에 여러개의 value를 저장할 수 있는 특징을 가졌습니다. 값의 저장 방법은 map과 동일하며 []를 사용하여 자동으로 값을 넣어주는 방법은 사용하지 못합니다. 선언방
rshday.tistory.com
https://eocoding.tistory.com/6
hash_map | unordered_map | map 차이 비교, 특징 정리 - C++
hash_와 unordered_에 대하여 hash라는 말이 붙지 않은 map,set은 자료를 정렬해서 저장합니다. (key를 기준으로 오름차순 정렬) 따라서 순회할 때도 저장된 데이터를 넣은 순서대로가 아닌 자동정렬된
eocoding.tistory.com
다른 사람 코드
https://leeeegun.tistory.com/5
[C++ STL] Sort() 사용법 및 compare 함수
sort 함수는 C++ STL에서 제공하는 함수로써 정렬에 이용되며 헤더를 include 하여 사용 할 수 있다. 각종 알고리즘 문제에서도 간단하게 사용 할 수 있어서 자주 쓰이는데, 이 함수의 시간 복잡도는 n
leeeegun.tistory.com
https://breakcoding.tistory.com/117
[C++] vector (벡터) 정렬, 배열 정렬하기
정렬을 하려면 라이브러리의 sort() 함수를 쓰면 된다. 따라서 헤더파일을 포함해줘야 한다. sort() 함수의 첫번째 두번째 매개변수는 iterator, 즉 포인터이다. sort - C++ Reference custom (2)template void s..
breakcoding.tistory.com
'Algorithm > Programers - C++' 카테고리의 다른 글
[프로그래머스]문자열 다루기 기본 / multiset, sort (0) | 2022.02.12 |
---|---|
[프로그래머스]문자열 내 p와 y의 개수 (0) | 2022.02.12 |
[프로그래머스]스택/큐 - 주식가격 (0) | 2022.02.08 |
[프로그래머스] 같은 숫자는 싫어 / unique (0) | 2022.02.08 |
[프로그래머스] 부족한 금액 계산하기 (0) | 2022.02.07 |