[Programmers] #181894 - 2의 영역 [Java][C++][Python]
[Programmers] #181894 - 2의 영역 [Java][C++][Python]
1. 아이디어
연속된 부분 배열이 모든 2를 담으려면 첫 번째 2와 마지막 2를 포함해야 하고, 그 사이는 연속이라 저절로 포함된다. 그보다 앞이나 뒤는 필요 없으므로 첫 번째 2부터 마지막 2까지가 가장 작은 구간이다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
int n = arr.length;
int s = 0, e = n - 1;
while (s < n && arr[s] != 2) {
s++;
}
if (s == n) return new int[]{-1};
while (arr[e] != 2) {
e--;
}
return Arrays.copyOfRange(arr, s, e + 1);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(vector<int> arr) {
int n = arr.size();
int s = 0, e = n - 1;
while (s < n && arr[s] != 2) s++;
if (s == n) return {-1};
while (arr[e] != 2) e--;
return vector<int>(arr.begin() + s, arr.begin() + e + 1);
}
1
2
3
4
5
def solution(arr):
idx = [i for i, x in enumerate(arr) if x == 2]
if not idx:
return [-1]
return arr[idx[0] : idx[-1] + 1]
This post is licensed under CC BY 4.0 by the author.