
프로그래머스 LV1 달리기경주 JavaScript

순차적으로 calling의 원소에대해 players에서의 index를 찾고,
players배열에서 해당index와 index-1 의 자리를 바꿔주는 방식으로 코드를 짰습니다.
function solution(players, callings) {
callings.map((e) => {
const index = players.indexOf(e);
const temp = players[index];
players[index] = players[index - 1];
players[index - 1] = temp;
});
return players
}

하지만 , 시간초과 발생..
문제에선 시간제약에대해 안적혀있었는데 ..
indexOf로 배열을 순회해 index를 찾는 방식말고 , object = {"mumu":0 , "soe":1 ...} 객체를 만들어
객체에 value값으로 index를 구해주겠습니다.
function solution(players, callings) {
const object = {};
for (i = 0; i < players.length; i++) {
object[players[i]] = i;
}
callings.forEach((v) => {
const index = object[v];
const temp = players[index];
players[index] = players[index - 1];
players[index - 1] = temp;
object[v] = index - 1;
object[players[index]] = index;
});
return players;
}
callings를 순회하며 해당 원소가 key인 value의 값을 index에 저장합니다.
players 에서 순서를 스왑해줍니다.
object 객체의 값들도 바꿔줍니다.
해당 방식으로 배열을 순회하여 index를 찾지않고 객체에 접근하여 index를 가져옵니다!
'Algorithm' 카테고리의 다른 글
자료구조 Trie (0) | 2024.09.29 |
---|---|
LeetCode 회문 문자열 찾기 (0) | 2024.09.19 |