코딩테스트/프로그래머스

[프로그래머스] Python3 2의 영역

Developer D 2024. 1. 6. 20:06

문제 설명
정수 배열 arr가 주어집니다. 배열 안의 2가 모두 포함된 가장 작은 연속된 부분 배열을 return 하는 solution 함수를 완성해 주세요.
단, arr에 2가 없는 경우 [-1]을 return 합니다.

def solution(arr):
    answer = []
    
    min_index = 0
    max_index = 0
    
    count = False
    
    for i in range(len(arr)):
        if arr[i] == 2:
            min_index = arr.index(2)
            count = True
            min_index = min(min_index,i)
            max_index = max(max_index,i)
        else :
            pass
    
    if count :
        for i in range(min_index, max_index+1):
            answer.append(arr[i])
    else :
        answer.append(-1)
            
    return answer
반응형