개발쿠키

[프로그래머스]프로세스(java) 본문

개발/baekjoon&programmers

[프로그래머스]프로세스(java)

쿠키와개발 2023. 6. 30. 22:40

https://school.programmers.co.kr/learn/courses/30/lessons/42587

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

대략 35분 정도 걸린거 같다^^...


public int solution(int[] priorities, int location) {
    int answer = 0;

    //우선순위 큐
    Queue<Integer> prio = new LinkedList<>();
    //위치 즉 location 큐
    Queue<Integer> idx = new LinkedList<>();

    //우선순위 큐는 그대로 넣고, location은 순서대로 초기화 
    for (int i = 0; i < priorities.length; i++) {
        prio.add(priorities[i]);
        idx.add(i);
    }

    int maxVal = findMax(prio);  //1.최고 순위 값 조회
    int cnt = 0;  //cnt는 빠진 순서다 첫번재로 빠지면 1 두번째로 빠지면 2 ...

    while(!prio.isEmpty()) {
        //2. 우선순위 최고값 보다 작을 경우
        if (prio.peek() < maxVal) {
            //우선순위 큐에서 빼서 뒤로 보낸다. location의 값도 동시에 뒤로 보낸다. 
            prio.offer(prio.poll()); 
            idx.offer(idx.poll());
        } else if (prio.peek() == maxVal) { //3. 우선순위 최고값과 같을 경우
            prio.poll(); //최고 우선순위 뺌
            int now = idx.poll(); //위치 확인
            cnt++; //cnt 증가 빠졌으니까
            //찾고자 하는 locaiton과 같을경우 몇번째로 빠졌는지(cnt) 할당 후 break;
            if (now == location) {
                answer = cnt;
                break;
            }

            // 그게 아니라면 우선순위 최고값 갱신 후 다시 while문 위로
            maxVal = findMax(prio);
        }
    }

    return answer;
}

//우선순위 최고값 찾는 메소드
private int findMax(Queue<Integer> priorities) {
    int max = Integer.MIN_VALUE;
    for (int v : priorities) {
        if (v > max) {
            max = v;
        }
    }
    return max;
}

코드가 좀 길다...다 풀고 다른 사람 풀이를 보다가 내가 구현한 findMax와 같은 역할을 하는 Collection.max라는 메소드와 java 8에서 추가된 Stream max 메소드가 있는걸 알았다.

 

다음에는 해당 메소드들을 활요해서 풀어봐야겠다. ㅎㅎ