개발공부/코딩테스트 연습문제

[프로그래머스] Level.2 - 프린터 (JAVA)

ku-na 2022. 1. 26. 14:37

문제 설명과 제한사항

풀이

import java.util.*;

class Solution {
    public int solution(int[] priorities, int location) {
        int count = 0;
        List<print> pl = new ArrayList<print>();
        
        for(int i = 0 ; i < priorities.length; i++){
            pl.add(new print(i, priorities[i]));
        }
        while(!pl.isEmpty()){
            print p = pl.remove(0);
            
            for(int i = 0 ; i < pl.size(); i++){
                if(pl.get(i).priority > p.priority) {
                    pl.add(pl.size(), p);
                    break;
                }
                if(i == pl.size()-1) {
                    count++;
                    if(p.index == location){
                        return count;
                    }
                }
            }
        }
        return count;
    }
    
    public class print{
        int index;
        int priority;
        print(int index, int priority){
            this.index = index;
            this.priority = priority;
        }
    }
}

 

+++

우선 1차 풀이다

100점을 받지 못했기 때문이다.

 

 

 

우선 반복문을 겹치고 겹치고 겹쳐 하드코딩으로 풀어본 결과 시간초과가 뜬다. (당연한 이야기)

그래서 흠.. 스택이라고 써있었는데.. 스택을 써볼까..

하다가 비교하고 마지막에 넣는 과정때문에 또 시간이 초과한다.

그리하여 나만의 작은 스택을 만들었다. print 객체는 대기 목록의 인덱스(로케이션과 비교를 위함)와 중요도를 저장하고

print 객체로 List같은 스택을 만들었다. 근데 왜 3개나 틀렸을까..

그리고 다시 생각해보니 큐로 풀면 될거 같은.. 아니 그냥 리스트로 풀면 되겠..? 어 뭐야 씹..

이렇게 정신을 차리고 보니.. 문제에 스택이라고 써 있는게 아닌 스택/큐라고 써있었고

나는 뻘짓에 얼굴이 시뻘게 져서 울그락 불그락 코드를 다시 바꿨다.

이제 나도 모르겠으니까 짜증나니까 말걸지 마세요.

그래서 오늘은 여기까지 풀 것 임.!

 

+++++++

최종 풀이

import java.util.*;

class Solution {
    public int solution(int[] priorities, int location) {
        int count = 0;
        Queue<print> pq = new LinkedList<print>();
        
        for(int i = 0 ; i < priorities.length; i++){
            pq.offer(new print(i, priorities[i]));
        }
        while(!pq.isEmpty()){
            print p = pq.poll();
            boolean check = true;
            for(print tmp : pq){
                if(tmp.priority > p.priority){
                    pq.offer(p);
                    check = false;
                    break;
                } 
            }
            if(check) {
                count++;   
                if(p.index == location) return count;
            }
        }
        return count;
    }
    
    public class print{
        int index;
        int priority;
        print(int index, int priority){
            this.index = index;
            this.priority = priority;
        }
    }
}

그냥 헛짓거리 안하고 큐로 했음..

사실 간과하고 있던 사실은 큐나 스택이나 뭐든 foreach로 슥 둘러볼 수 있다는 것임.. 미쳐 상상도 못하고 있다가

다른 사람 코드 보고 참고해서... 어 큐로 그냥 슥슥 풀어볼까..? 했음 그래서 풀림 뭐임..? 근데 그 전코드랑 다를게 무엇임..?