프로그래머스 실패율 자바

BioBeBE·2022년 8월 2일
0

프로그래머스

목록 보기
36/40

문제풀이

  1. 이중 for(스테이지(사람))문 돌며 실패율의 분모로 들어갈 값을 max로 정하고 한사이클마다 실패율을 ArrayList에 넣고 max에서 cnt(해당 스테이지에 해당하는 사람) 빼줌
  2. Comparable Interface 사용 compareTo method 실패율 내림차순, 실패율이 같으면 stage 오름차순으로 반환
  3. Collections.sort로 compareto로 ArrayList 정렬
  4. ArrayList > answer return

알고리즘은 맞는데 시간이 너무 오래걸림

코드

import java.util.*;
class Point implements Comparable<Point>{
    int stage;
    Float rate;
    Point(int s, float r){
        this.stage = s;
        this.rate= r;
    }
    @Override
    public int compareTo(Point x){
        if(x.rate == this.rate)return (this.stage - x.stage);
        else {
            double com= x.rate - this.rate;
            if(com>0) return 1;
            if(com<0) return -1;
            return 0;
        }
    }
}
class Solution {
    public int[] solution(int N, int[] stages) {
        int[] answer = new int[N];
        ArrayList<Point> arr = new ArrayList<>();
        int max = stages.length;
        for(int i=1;i<=N;i++){
            int cnt=0;
            for(int j=0;j<stages.length;j++){
                if(i==stages[j])cnt++;
            }
            arr.add(new Point(i, (float)cnt/max));
            max-=cnt;
        }
        Collections.sort(arr);
        for(int i=0;i<N;i++){
            answer[i]=arr.get(i).stage;
        }
        return answer;
    }
}
profile
개발자지망생

0개의 댓글