Algorithm/C++ - 프로그래머스

프로그래머스 level2 - 가장 큰 수 C++

ㅇㅇ잉 2021. 4. 6. 20:59

맨 처음에 이걸 어떻게 쪼개서 하나하나 배치하지..하면서 단순 정렬로만 생각하면서 시간이 좀 걸렸던 문제.

 

string vector로 받아서, string을 비교해주면서 정렬해준다.

근데 이제 그냥 정렬해주는 것이 아니라 커스텀 함수를 곁들인.

그걸 comp함수를 통해 설정해주는데, 조건이 a+b > b+a이다.

주어진 예에서 [3, 30, 34, 5, 9] 커스텀 함수를 통해 정렬하게되면

3,30이면 3+30=330, 30+3=303이므로 더 큰수로 만들어지는 330이 맞다.

 

* 비교함수에서 bool comp(string a, string b) 이렇게 하지 않고

bool comp(const string &a, const string &b) 이렇게 사용하는 이유는 copy construct되지 않아서 메모리를 효율적으로 쓰는 장점이 있어서이다.

 

 

 

<정리>

1. string vector에 numbers 원소들 넣어줌.

2. 문자열을 더하여 앞자리가 같더라도 정렬해줄 수 있게 comp함수 작성.

3. answer에 넣어줌.

4. 만약 answer[0]=='0'이면 가장 큰 수는 0이므로, 0을 return해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
 
bool comp(const string &a, const string &b){
    return a+> b+a;
}
 
string solution(vector<int> numbers) {
    string answer = "";
    
    vector<string> tmp;
    
    for(int i=0;i<numbers.size();i++) tmp.push_back(to_string(numbers[i]));
    
    sort(tmp.begin(),tmp.end(),comp);
    
    for(int i=0;i<tmp.size();i++) answer+=tmp[i];
    
    if(answer[0]=='0'return "0";
    
    return answer;
}
cs