문제
나의 풀이
class Solution {
public int solution(int n, int[] lost, int[] reserve) {
int answer = 0;
int cnt = 0;
for (int i = 0; i < lost.length; i++) {
for (int j = 0; j < reserve.length; j++) {
if (lost[i] != 0 && reserve[j] != 0 && lost[i] == reserve[j]) {
lost[i] = 0;
reserve[j] = 0;
cnt++;
}
}
}
for (int i = 0; i < lost.length; i++) {
for (int j = 0; j < reserve.length; j++) {
if (lost[i] != 0 && reserve[j] != 0 && (lost[i] - 1 == reserve[j]) || (lost[i] + 1 == reserve[j])) {
lost[i] = 0;
reserve[j] = 0;
cnt++;
}
}
}
answer = n - lost.length + cnt;
return answer;
}
- 통과하지 못하는 테스트케이스가 있었는데 정렬을 통해 해결해야한 다는 것을 알았다.
sort 정렬 풀이
import java.util.Arrays;
class Solution {
public int solution(int n, int[] lost, int[] reserve) {
int answer = 0;
int cnt = 0;
Arrays.sort(lost);
Arrays.sort(reserve);
for (int i = 0; i < lost.length; i++) {
for (int j = 0; j < reserve.length; j++) {
if (lost[i] == reserve[j]) {
lost[i] = 0;
reserve[j] = 0;
cnt++;
}
}
}
for (int i = 0; i < lost.length; i++) {
for (int j = 0; j < reserve.length; j++) {
if (lost[i] != 0 && reserve[j] != 0 && (lost[i] - 1 == reserve[j]) || (lost[i] + 1 == reserve[j])) {
lost[i] = 0;
reserve[j] = 0;
cnt++;
}
}
}
answer = n - lost.length + cnt;
return answer;
}
- 처음에
Arrays.stream(lost).sorted();
로 정렬을 시도했고 틀렸다.
sort 방법
Arrays.stream(lost).sorted();
Arrays.stream(reserve).sorted();
System.out.println(Arrays.toString(lost));