import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
int answer = 0;
Queue <Document> qu = new LinkedList<>();
Integer [] prioritiesClone = new Integer[priorities.length];
for (int i = 0 ; i < priorities.length ; i++){
qu.add(new Document(priorities[i], i));
prioritiesClone[i] = priorities[i];
}
Arrays.sort(prioritiesClone, Collections.reverseOrder());
for (int i = 0 ; !qu.isEmpty() ;){
if(qu.peek().getPriority() == prioritiesClone[i]){
if (qu.peek().getId() == location){
return i + 1;
} else {
i++;
qu.poll();
}
} else {
qu.add(qu.poll());
}
}
return answer;
}
}
class Document{
int priority;
int id;
public Document(int priority, int id){
this.priority = priority;
this.id = id;
}
public int getPriority(){
return priority;
}
public int getId(){
return id;
}
}
기존코드
import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
int answer = 1;
ArrayList<PriorityCounter> priorityArrayList = new ArrayList<>();
HashMap <Integer, Integer> priorityMap = new HashMap<>();
Queue <Item> itemQueue = new LinkedList();
for(int i = 0 ; i < priorities.length ; i ++){
itemQueue.add(new Item(priorities[i], i));
priorityMap.put(priorities[i], priorityMap.getOrDefault(priorities[i] , 0) + 1);
}
for( Integer key : priorityMap.keySet() ){
priorityArrayList.add(new PriorityCounter(key, priorityMap.get(key)));
}
priorityArrayList.sort(Comparator.reverseOrder());
Item item;
int i = 0;
while (!itemQueue.isEmpty()){
item = itemQueue.poll();
if(item.getPriority() == priorityArrayList.get(i).getPriority()){
if(item.getLocation() == location){
return answer;
} else{
priorityArrayList.set(i, new PriorityCounter(priorityArrayList.get(i).getPriority(), priorityArrayList.get(i).getCount() - 1));
if (priorityArrayList.get(i).getCount() == 0){
i ++;
}
answer ++;
}
} else{
itemQueue.add(item);
}
}
return answer;
}
class Item {
int priority;
int location;
public Item(int priority, int location){
this.priority = priority;
this.location = location;
}
public int getPriority(){
return this.priority;
}
public int getLocation(){
return this.location;
}
}
class PriorityCounter implements Comparable<PriorityCounter> {
int priority;
int count;
public PriorityCounter(int priority, int count){
this.priority = priority;
this.count = count;
}
public int getPriority(){
return this.priority;
}
public int getCount(){
return this.count;
}
@Override
public int compareTo(PriorityCounter o) {
return this.getPriority() - o.getPriority();
}
}
}
'프로그래머스 - JAVA' 카테고리의 다른 글
코딩테스트 연습 > 스택/큐 > 주식가격 (0) | 2021.06.12 |
---|---|
코딩테스트 연습 > 스택/큐 > 다리를 지나는 트럭 (0) | 2021.06.12 |
코딩테스트 연습 > 스택/큐 > 기능개발 (0) | 2021.06.12 |
코딩테스트 연습 > 해시 > 베스트앨범 (0) | 2021.06.12 |
코딩테스트 연습 > 해시 > 위장 (0) | 2021.06.12 |