[프로그래머스] 실패율

2020. 3. 24. 16:43프로그래머스/카카오

import java.util.*;

class Solution {
    public int[] solution(int N, int[] stages) {
        int[] answer = new int[N];
        ArrayList<Integer> temp = new ArrayList<>();
        double[] failrate = new double[N+1];
        double[] copymap = new double[N+1];
        
        for(int i=1; i<=N;i++){
            int all = 0;
            int stay = 0;
            for(int j=0; j<stages.length; j++){
                if(stages[j]>=i){
                    all ++;
                }
                if(stages[j]==i){
                    stay ++;
                }
            }
            if(all!=0){
            failrate[i] = (double) stay/all;
            }else{
                failrate[i] = (double)0;
            }
        }
        
        
        for(int i=1; i<copymap.length; i++){
            copymap[i] = failrate[i];
        }
        
      Arrays.sort(failrate);
      
        for(int i=N; i>=1; i--){
            for(int j=1; j<copymap.length; j++){
                if(copymap[j]==failrate[i]){
                    if(!temp.contains(j)){
                        temp.add(j);
                    }
                }
            }
        }
        
        for(int i=0; i<temp.size(); i++){
            answer[i] = temp.get(i);
        }
     
        return answer;
    }
}

 

두번째 풀때는 각 단계와 실패율을 갖는 클래스를 만들어서 풀었다.

import java.util.*;

class Solution {
    class failSet{
        double failrate;
        int step;
        
        failSet(double failrate, int step){
            this.failrate = failrate;
            this.step = step;
        }
   
    }
    
    public int[] solution(int N, int[] stages) {
        int[] answer = {};
        
        List<failSet> failRate = new ArrayList<>();
        
        for(int i=1; i<=N; i++){
            int all=0;
            int stay=0;
            
            for(int j=0; j<stages.length; j++){
                if(stages[j]>=i){
                    all++;
                }
                if(stages[j]==i){
                    stay++;
                }
            }
            if(all==0){
             failRate.add(new failSet((double)0,i));   
            } else {
            failRate.add(new failSet((double)stay/all,i));
            }
        }
       
      Collections.sort(failRate, new Comparator<failSet>(){
          public int compare(failSet s1, failSet s2){
              if (s2.failrate>s1.failrate){
                  return 1;
              }else if (s1.failrate==s2.failrate){
                  return 0;
              } else{
                  return -1;
              }
          }
      });
        
      answer = new int[failRate.size()];
        
        for(int i=0; i<answer.length; i++){
            answer[i] = failRate.get(i).step;
        }
        
        
        return answer;
    }
}

객체형 리스트를 정렬할때는 Comparator를 확장하여 기준을 정해주어 할 수 있다.