
아래는 프로그래머스에서 제공한 문제 설명입니다.
정수 배열 arr가 주어집니다. 배열 안의 2가 모두 포함된 가장 작은 연속된 부분 배열을 return 하는 solution 함수를 완성해 주세요.
단, arr에 2가 없는 경우 [-1]을 return 합니다.
using System;
using System.Collections.Generic;
public class Solution {
public int[] solution(int[] arr) {
List<int> answer = new List<int>();
int firstIndex = -1;
int secondIndex = -1;
for(int i = 0; i < arr.Length; i++)
{
if(arr[i] == 2)
{
if(firstIndex == -1)
firstIndex = i;
secondIndex = i;
}
}
// 2가 없다면 [-1] 반환
if(firstIndex == -1)
return new int[] {-1};
else
{
for(int i = firstIndex; i <= secondIndex; i++)
answer.Add(arr[i]);
}
return answer.ToArray();
}
}