Backdrop

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

2의 영역
0

문제 설명

정수 배열 arr가 주어집니다. 배열 안의 2가 모두 포함된 가장 작은 연속된 부분 배열을 return 하는 solution 함수를 완성해 주세요.

단, arr에 2가 없는 경우 [-1]을 return 합니다.

제한사항

  • 1 ≤ arr의 길이 ≤ 100,000
    • 1 ≤ arr의 원소 ≤ 10

입출력 예

arrresult
[1, 2, 1, 4, 5, 2, 9][2, 1, 4, 5, 2]
[1, 2, 1][2]
[1, 1, 1][-1]
[1, 2, 1, 2, 1, 10, 2, 1][2, 1, 2, 1, 10, 2]

입출력 예 설명

입출력 예 #1

  • 2가 있는 인덱스는 1번, 5번 인덱스뿐이므로 1번부터 5번 인덱스까지의 부분 배열인 [2, 1, 4, 5, 2]를 return 합니다.

입출력 예 #2

  • 2가 한 개뿐이므로 [2]를 return 합니다.

입출력 예 #3

  • 2가 배열에 없으므로 [-1]을 return 합니다.

입출력 예 #4

  • 2가 있는 인덱스는 1번, 3번, 6번 인덱스이므로 1번부터 6번 인덱스까지의 부분 배열인 [2, 1, 2, 1, 10, 2]를 return 합니다.

풀이

이론

Array.prototype.includes()

includes() 메서드는 배열의 항목에 특정 값이 포함되어 있는지를 판단하여 적절히 true 또는 false를 반환해요.

includes(searchElement[, fromIndex])
  • searchElement : 배열에서 찾을 값
  • fromIndex : 검색을 시작할 인덱스. 음수를 지정하면 배열의 끝에서부터 검색을 시작해요. 기본값은 0이에요.
const array1 = [1, 2, 3];
 
console.log(array1.includes(2));
// Expected output: true
 
const pets = ['cat', 'dog', 'bat'];
 
console.log(pets.includes('cat'));
// Expected output: true
 
console.log(pets.includes('at'));
// Expected output: false

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.indexOf()

indexOf() 메서드는 배열에서 주어진 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고, 찾을 수 없는 경우 -1을 반환해요.

indexOf(searchElement[, fromIndex])
  • searchElement : 배열에서 찾을 요소
  • fromIndex : 검색을 시작할 인덱스. 음수인 경우 배열의 끝에서부터 요소를 찾아요. 기본값은 0이에요.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
 
console.log(beasts.indexOf('bison'));
// Expected output: 1
 
// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4
 
console.log(beasts.indexOf('giraffe'));
// Expected output: -1

코드

function solution(arr) {
  if (!arr.includes(2)) {
    return [-1];
  }
 
  return arr.slice(arr.indexOf(2), arr.lastIndexOf(2) + 1);
}