class Solution {
public int[] solution(int[] arr) {
int[] answer = {};
return answer;
}
}
해결법
방법 1
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
int min = 100000;
int max = 1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 2) {
min = Math.min(min, i);
max = Math.max(max, i);
}
}
if (min <= max) {
return Arrays.copyOfRange(arr, min, max + 1);
} else {
return new int[]{-1};
}
}
}
방법 2
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
ArrayList<Integer> list = new ArrayList<>();
int frontIdx = -1;
int backIdx = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 2) {
frontIdx = i;
break;
}
}
for (int j = arr.length-1; j >= 0; j--) {
if (arr[j] == 2) {
backIdx = j;
break;
}
}
if (frontIdx == -1 && backIdx == -1) {
list.add(-1);
} else {
for (int i = frontIdx; i <= backIdx; i++) {
list.add(arr[i]);
}
}
int[] answer = new int[list.size()];
for(int i = 0; i < answer.length; i++) {
answer[i] = list.get(i);
}
return answer;
}
}
2의 영역 Lv. 0