

나의 풀이
import java.util.*;
class Solution {
public int solution(int n, int[] lost, int[] reserve) {
int answer = n - lost.length; // 1
boolean[] checkLost = new boolean[lost.length]; // 2
boolean[] checkReserve = new boolean[reserve.length];
Arrays.sort(reserve);
Arrays.sort(lost);
for (int i = 0; i < l ost.length; i++) { // 3
for (int j = 0; j < reserve.length; j++) {
if (lost[i] == reserve[j]) {
checkLost[i] = true;
checkReserve[j] = true;
answer++;
}
}
}
for (int i = 0; i < lost.length; i++) { // 4
for (int j = 0; j < reserve.length; j++) {
if (lost[i] - 1 == reserve[j] && checkReserve[j] == false && checkLost[i] == false) {
checkReserve[j] = true;
checkLost[i] = true;
answer++;
} else if (lost[i] + 1 == reserve[j] && checkReserve[j] == false && checkLost[i] == false) {
checkReserve[j] = true;
checkLost[i] = true;
answer++;
}
}
}
return answer;
}
}
과정
- answer은 전체 학생의 수 n에서 체육복을 도난당한 학생들의 배열 lost의 길이를 빼준값으로 초기화
- lost배열과 reserve배열이 사용되었는지 체크할 boolean배열을 두개 만들어주고(boolean의 기본값은 false), lost와 reserve를 오름차순 정렬
- 일단 여벌의 체육복을 가져온 학생이 체육복을 도난당했을 때의 상황을 제거한다. lost와 reserve에 같은 값이 있으면 빌려줄 수 없기에 check를 true로 바꾸고, answer을 증가
- lost[i]의 +1, -1인 값이 reserve[j]에 있고, checkLost와 checkReserve가 둘 다 false라면 두 배열을 true로 바꿔주고, answer을 증가
다른 사람 풀이
class Solution {
public int solution(int n, int[] lost, int[] reserve) {
int[] people = new int[n];
int answer = n;
for (int l : lost)
people[l-1]--;
for (int r : reserve)
people[r-1]++;
for (int i = 0; i < people.length; i++) {
if(people[i] == -1) {
if(i-1>=0 && people[i-1] == 1) {
people[i]++;
people[i-1]--;
}else if(i+1< people.length && people[i+1] == 1) {
people[i]++;
people[i+1]--;
}else
answer--;
}
}
return answer;
}
}