Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags more
Archives
Today
Total
관리 메뉴

David의 블로그

프로그래머스 - 2의 영역 본문

프로그래밍/코딩

프로그래머스 - 2의 영역

David 리 2024. 6. 23. 23:39

문제설명>

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

 

내 생각>

먼저 2로 시작하는 인덱스 값과 2로 끝나는 인덱스 값을 담아줄 ArrayList intList를 선언하고

add해줬다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 2의 영역
//        [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]
        
        int[] arr = {111};
        int[] answer = {};
        
        
        List<Integer> intList = new ArrayList<Integer>();
        List<Integer> resList = new ArrayList<Integer>();
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == 2) {
                intList.add(i);
            }
        }
        
        if (intList.isEmpty()) {
            resList.add(-1);
        } else {
            for (int i = intList.get(0); i <= intList.get(intList.size() - 1); i++) {
                System.out.println(arr[i]);
                resList.add(arr[i]);
            }
        }
        answer = resList.stream().mapToInt(i -> i).toArray();
cs

intList에 isEmpty()를 이용하여 2가 없다면, -1을 리턴해 줄 것이고

intList에 담겨있는 값들에서 첫번째와 마지막값이 우리가 뽑아내야 할 범위의 인덱스이니

이것으로 for문을 돌려줬다.