
해결방법
- 이 문제는 정렬(sort)을 활용하여 풀 수 있음
- 제한 사항에 "정답이 너무 크니 문자열로 바꿔라"라고 있는데, int 형 배열 numbers를 string 배열로 바꾼 후, 정렬을 해줄 때 3번째 인자의 함수에서 커스텀 비교 함수를 넣어주면 됨
- 처음에는 sort 함수에서 to_string으로 바꿔서 numbers 배열의 순서를 바꿨었는데 시간초과가 되었음 🙁
참고사항

stl에서 제공하는 sort 함수의 파라미터는 위와 같습니닷
세 번째 파라미터가 뽀인트인데, 비교하고 싶은 두 개의 요소(인자)랑 return 값을 맞춰서 작성해줘야 합니다.
이 문제의 경우에는 조건을 숫자 1과 숫자 2를 붙여서 비교했을 때 더 큰 값만 넣어주면 됩니다.
예를 들어서, "6"과 "10"을 비교 시, 610 또는 106이 나오는데 610이 더 크니까, 6→10으로 sort 해주면 됩니다.
코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <vector> | |
#include <iostream> | |
#include <algorithm> | |
using namespace std; | |
bool compare(string str1, string str2) | |
{ | |
return str1 + str2 > str2 + str1; | |
} | |
string solution(vector<int> numbers) { | |
string answer = ""; | |
vector<string> array; | |
for(auto num :numbers) | |
{ | |
array.push_back(to_string(num)); | |
} | |
sort(array.begin(), array.end(), compare); | |
for(auto num :array) | |
{ | |
answer += num; | |
} | |
if(array[0] == "0") return "0"; | |
return answer; | |
} |
'CS > 프로그래머스' 카테고리의 다른 글
프로그래머스 - level3/있었는데요 없었습니다/MySql (0) | 2023.05.19 |
---|---|
프로그래머스 - level3/베스트 앨범/C++ (2) | 2023.05.17 |
프로그래머스 - level 3/최고의 집합/C++ (4) | 2023.05.12 |
프로그래머스 - 탐욕법(Greedy)/체육복/C++ (0) | 2021.08.02 |
프로그래머스 - 완전탐색/모의고사/C++ (0) | 2021.07.30 |