- 문제 풀이
"정렬"을 이용하는 문제였다.
- 코드
처음에 작성한 코드는 다음과 같다.
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int solution(vector<int> citations) {
int answer = 0;
sort(citations.begin(), citations.end());
int count = 0;
for(int i=citations.size()-1; i>=0; i--) {
count = 0;
for(int j=0; j<citations.size(); j++) {
if( citations[i]<=citations[j] ) {
count++;
}
}
if( count==citations[i]&&citations[i-1]<=count ) {
answer = count;
break;
}
}
return answer;
}
하지만 오류가 발생했다.

또 정렬할 때 그냥 두번 일 하지 않아도 되도록 처음부터 내림차순으로 정렬하도록 했다.
중첩 for문을 사용하지 않아도 for문 하나로 간단하게 문제를 해결할 수 있었다.
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> citations) {
int answer = 0;
sort(citations.begin(), citations.end(), greater<int>());
if (!citations[0])
return 0;
for (int i = 0; i < citations.size(); i++) {
if (citations[i] > i)
answer++;
else
break;
}
return answer;
}
(코드 참고: https://mungto.tistory.com/27)
'프로그래머스' 카테고리의 다른 글
| 소수 찾기 - 프로그래머스, c++ (0) | 2023.01.31 |
|---|---|
| 모의고사 - 프로그래머스, c++ (0) | 2023.01.30 |
| 최소직사각형 - 프로그래머스, c++ (0) | 2023.01.28 |
| 가장 큰 수 - 프로그래머스, c++ (0) | 2023.01.28 |
| 프린터 - 프로그래머스, c++ (0) | 2023.01.27 |