[C++]
#include <string>
#include <vector>
#include <algorithm> //pair, count, sort
using namespace std;
bool compare(const pair<double, int> &a, const pair<double, int> &b){
if (a.first > b.first)
return true; // >내림차순
else if (a.first == b.first)
return a.second < b.second; // <오름차순
else
return false;
}
vector<int> solution(int N, vector<int> stages) {
vector<int> answer(0);
int cnt[501] = { 0 };
vector<pair<double, int>> rate; //(실패율,스테이지번호) 벡터로
for (int i = 1; i <= N + 1; i++){ //stages 카운트한거 - cnt[i]에 저장
cnt[i] = count(stages.begin(), stages.end(), i);
}
double down = stages.size();
for (int i = 1; i <= N; i++){ //(실패율,스테이지번호) 저장
if (down != 0){
rate.push_back(make_pair(cnt[i] / down, i));
down -= cnt[i];
}
else
rate.push_back(make_pair(0, i)); //분모 0인경우 실패율0으로 처리
}
sort(rate.begin(), rate.end(), compare); //실패율 기준으로 내림차순 정렬
for (int i = 0; i < rate.size(); i++){
answer.push_back(rate[i].second);
}
return answer;
}
[JAVA]
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Solution {
static class Rate implements Comparable<Rate> {
int index; double rate;
public Rate(int index, double rate){
this.index=index; this.rate=rate;
}
@Override
public int compareTo(Rate r){
if(this.rate>r.rate) //실패율 내림차순
return -1;
else if(this.rate==r.rate)
if(this.index>r.index) //인덱스 오름차순
return 1;
return 1;
}
}
public int[] solution(int N, int[] stages) {int[] count = new int[N+2];
for(int i=0; i<stages.length; i++){
count[stages[i]]++;
}
List<Rate> rate = new ArrayList<>(); //(인덱스,실패율) 저장할 리스트
double total = stages.length;
for(int i=1; i<N+1; i++){
if(total>0){
rate.add(new Rate(i,(double)count[i]/total));
total-=count[i];
}
else //분모=0 되면 실패율=0으로 저장
rate.add(new Rate(i, 0));
}
Collections.sort(rate); //정렬
int[] answer = new int[rate.size()];
for(int i=0; i<rate.size(); i++){
answer[i] = rate.get(i).index;
}
return answer;
}
}
'1d-1c > Programmers' 카테고리의 다른 글
Level1_다트게임 (JAVA) (0) | 2020.12.11 |
---|---|
Level1_비밀지도 (JAVA) (0) | 2020.12.11 |
Level2_카카오프렌즈 컬러링북 (JAVA) (0) | 2020.11.05 |
Level2_기능개발 (C++) (JAVA) (0) | 2020.11.05 |
Level1_체육복 (JAVA) (0) | 2020.11.02 |