본문 바로가기

LeetCode

1409. Queries on a Permutation With Key / TypeScript

Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:

  • In the beginning, you have the permutation P=[1,2,3,...,m].
  • For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i].

Return an array containing the result for the given queries.

 

Example 1:

Input: queries = [3,1,2,1], m = 5
Output: [2,1,2,1] 
Explanation: The queries are processed as follow: 
For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. 
For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. 
For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. 
For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. 
Therefore, the array containing the result is [2,1,2,1].  

Example 2:

Input: queries = [4,1,2,2], m = 4
Output: [3,1,2,0]

Example 3:

Input: queries = [7,5,5,8,3], m = 8
Output: [6,5,0,7,5]

 

출처 : https://leetcode.com/problems/queries-on-a-permutation-with-key/description/

 

풀이 

function processQueries(queries: number[], m: number): number[] {

    let p = Array.from({length:m},(_,index)=> index+1);
    let answer:number []=[];
    for(let query of queries){
       let pindex = p.indexOf(query);
       let el =p.splice(pindex,1)[0]
       p.unshift(el)
       answer.push(pindex)
    }
    return answer

};

 

주어진 쿼리 배열을 처리하여 특정 배열에서 각 쿼리가 위치한 인덱스를 찾아 결과로 반환하는 함수

 

  • 입력:
    • queries: 숫자 배열로, 각 쿼리를 나타냄.
    • m: 배열 p의 크기. 배열 p는 1부터 m까지의 숫자로 초기화.
  • 초기화:
    • p: 1부터 m까지의 숫자로 구성된 배열을 생성.
    • answer: 각 쿼리의 결과로 반환할 인덱스 값을 저장할 배열.
  • 쿼리 처리:
    • 주어진 queries 배열에서 각 쿼리 query를 순차적으로 처리.
    • query 값이 배열 p에서 몇 번째 인덱스에 위치하는지 찾음 (pindex).
    • 그 위치에 있는 요소를 배열 p에서 제거한 후(splice), 배열의 맨 앞에 삽입 (unshift).
    • 찾은 인덱스 값을 answer 배열에 추가.
  • 출력:
    • 모든 쿼리에 대해 위의 작업을 완료한 후, answer 배열을 반환

 

 

Array.from({length: m}, (_, index) => index + 1)

 

  • Array.from():
    • Array.from()은 유사 배열 객체 또는 반복 가능한 객체(예: 문자열, 배열, Set, Map 등)를 실제 배열로 변환하는 메서드.
    • 이 메서드는 두 가지 매개변수를 받을 수 있음
    • 하나는 배열로 변환할 객체이고, 다른 하나는 배열의 각 요소에 대해 호출할 맵핑 함수.
  • {length: m}:
    • Array.from 메서드에 전달된 첫 번째 인자는 객체.
    • 여기서 {length: m}은 길이가 m인 유사 배열 객체를 나타냄.
    • 유사 배열 객체는 배열처럼 인덱스가 있고, length 프로퍼티를 갖고 있지만 실제 배열은 아님.
  • (_, index) => index + 1:
    • 이 부분은 Array.from의 두 번째 매개변수로 전달된 맵핑 함수
    • 이 함수는 생성된 배열의 각 요소에 대해 호출됨.
    • 첫 번째 매개변수 _는 해당 요소의 값이지만, 여기서는 사용되지 않기 때문에 이름을 _로 지음.
    • 두 번째 매개변수 index는 현재 요소의 인덱스.
    • 이 함수는 단순히 인덱스에 1을 더한 값을 반환.
    • 즉, index가 0이면 1, index가 1이면 2를 반환.
  • 결과:
    • 이 코드는 1부터 m까지의 연속된 숫자를 요소로 갖는 배열을 생성.
    • 예를 들어, m = 5라면, 이 코드의 결과는 [1, 2, 3, 4, 5]

 

p.splice(pindex, 1)[0];

 

  • p.splice(pindex, 1):
    • splice는 배열에서 요소를 추가, 제거 또는 교체하는 메서드.
    • 첫 번째 매개변수 pindex는 제거할 요소의 인덱스를 지정.
    • 두 번째 매개변수 1은 pindex 위치에서 몇 개의 요소를 제거할지를 지정. 여기서는 하나의 요소만 제거.
    • 이 메서드는 제거된 요소들로 구성된 배열을 반환.
  • [0]:
    • splice 메서드는 배열을 반환하므로, [0]을 사용하여 그 배열의 첫 번째 요소를 가져옴.
    • 결과적으로, el에는 p 배열에서 제거된 특정 요소가 저장

 

p.unshift(el);

 

  • unshift는 배열의 맨 앞에 새로운 요소를 추가하는 메서드.
  • 이 메서드를 사용하면 기존 배열의 모든 요소가 한 칸씩 뒤로 밀리고, 추가된 요소가 배열의 첫 번째 요소가 됨.
  • 이 코드에서는 el을 배열 p의 맨 앞에 삽입