Backdrop

프로그래머스 ▸ 코딩 기초 트레이닝

수열과 구간 쿼리 2
0

문제 설명

정수 배열 arr와 2차원 정수 배열 queries이 주어집니다. queries의 원소는 각각 하나의 query를 나타내며, [s, e, k] 꼴입니다.

query마다 순서대로 sie인 모든 i에 대해 k보다 크면서 가장 작은 arr[i]를 찾습니다.

각 쿼리의 순서에 맞게 답을 저장한 배열을 반환하는 solution 함수를 완성해 주세요.
단, 특정 쿼리의 답이 존재하지 않으면 -1을 저장합니다.

제한사항

  • 1 ≤ arr의 길이 ≤ 1,000
    • 0 ≤ arr의 원소 ≤ 1,000,000
  • 1 ≤ queries의 길이 ≤ 1,000
    • 0 ≤ se < arr의 길이
    • 0 ≤ k ≤ 1,000,000

입출력 예

arrqueriesresult
[0, 1, 2, 4, 3][[0, 4, 2],[0, 3, 2],[0, 2, 2]][3, 4, -1]

입출력 예 설명

입출력 예 #1

  • 첫 번째 쿼리의 범위에는 0, 1, 2, 4, 3이 있으며 이 중 2보다 크면서 가장 작은 값은 3입니다.
  • 두 번째 쿼리의 범위에는 0, 1, 2, 4가 있으며 이 중 2보다 크면서 가장 작은 값은 4입니다.
  • 세 번째 쿼리의 범위에는 0, 1, 2가 있으며 여기에는 2보다 큰 값이 없습니다.
  • 따라서 [3, 4, -1]을 return 합니다.

풀이

이론

Array.prototype.slice()

slice() 메서드는 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환해요. 원본 배열은 바뀌지 않아요.

arr.slice([begin[, end]])
  • begin 또는 end 가 음수인 경우, 배열의 끝에서부터의 길이를 나타내요.
  • begin 이 생략된 경우, 0 번째 인덱스부터 추출해요.
  • end 가 생략된 경우, 배열의 끝까지 추출해요.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
 
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
 
console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]
 
console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]
 
console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]
 
console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]
 
console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

Array.prototype.filter()

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환해요.

filter(callbackFn[, thisArg])

callbackFn 함수는 세 가지 인자를 받아요.

  • element: 배열에서 처리되고 있는 현재 요소
  • index: 배열에서 처리되고 있는 현재 요소의 인덱스
  • array: filter를 호출한 배열
const words = [
  'spray',
  'limit',
  'elite',
  'exuberant',
  'destruction',
  'present',
];
const result = words.filter(word => word.length > 6);
 
console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]

Math.min()

  • Math.min() 함수는 주어진 숫자들 중 가장 작은 값을 반환해요.
Math.min([value1[, value2[, ...]]])
Math.min(2, 3, 1); // 1

구조 분해 할당을 사용하여 배열의 요소 중 가장 작은 값을 찾을 수 있어요.

const arr = [2, 3, 1];
Math.min(...arr); // 1

코드

function solution(arr, queries) {
  return queries.map(([s, e, k]) => {
    const filtered = arr.slice(s, e + 1).filter(x => x > k);
 
    return filtered.length ? Math.min(...filtered) : -1;
  });
}