반응형
문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
내 풀이
- 큐의 가장 큰 수 max 를 구한다.
- 큐에 하나만 남으면 return answer + 1
- 큐의 맨 앞을 뺀다(shift) (= process)
- process 가 max 와 동일하면,
- answer + 1
- 만약 location이 0이면(뺀 앞이라면) return answer
- max가 바뀌므로, max를 바꿔준다
- process와 max이 동일하지 않다면,
- 큐에 process 를 뒤에 추가한다 (push)
- location 을 앞으로 당긴다.
- -1을 하는데, location === -1 이 된다면 priorities.length - 1 로 두어 끝 인덱스 값으로 돌린다.
function solution(priorities, location) {
let answer = 0;
let max = Math.max(...priorities);
while(priorities.length) {
if(priorities.length === 1) return answer + 1;
const process = priorities.shift();
if(process === max) {
answer++;
max = Math.max(...priorities);
if(location === 0) return answer;
} else {
priorities.push(process)
}
location = (location - 1) === -1 ? priorities.length - 1 : location - 1;
}
}
다른 풀이 - 1
좋아요 많이 받은 풀이들을 보니까, 대부분 다 location 인지 아닌지, 혹은 원본의 인덱스와 같은 정보를 담은 객체를 만들고 풀었더라.
그리고 다 some 메서드를 사용했더라. (나는 max를 사용했는뎁)
function solution(priorities, location) {
let list = priorities.map((process, i) => ({ my: i === location, val: process })
};
let answer = 0;
while(true) {
let cur = list.shift();
if (list.some(t => t.val > cur.val) {
list.push(cur);
} else {
answer++;
if(cur.my) return answer;
}
}
}
다른 풀이 - 2
function solution(priorities, location) {
let arr = priorities.map((process, idx) => ({ idx, process });
const queue = [];
while(arr.length) {
let firstEle = arr.shift();
let hasHighPriority = arr.some(el => el.process > firstEl.process);
if(hasHighPriority) arr.push(firstEl);
else queue.push(firstEl);
}
return queue.findIndex(queueEl => queueEl.idx === location) + 1;
}
반응형
'CS > 알고리즘' 카테고리의 다른 글
[230427] 과일 장수 (0) | 2023.04.27 |
---|---|
[230423] 소수 만들기 (0) | 2023.04.23 |
[230423] 연속 부분 수열 합의 개수 (0) | 2023.04.23 |
[230423] 명예의 전당 (1) | 2023.04.23 |
[230422] 기능개발 (0) | 2023.04.22 |