
내가 작성한 코드
class Solution {
public int solution(int n, int[] lost, int[] reserve) {
int answer = n - lost.length; // 도둑맞지 않은 학생 수
boolean[] hasExtra = new boolean[n + 1]; // 여벌 체육복을 가지고 있는 학생 표시
boolean[] isLost = new boolean[n + 1]; // 도둑맞은 학생 표시
// 각 배열 초기화
for (int i : reserve) {
hasExtra[i] = true;
}
for (int i : lost) {
isLost[i] = true;
}
// 여벌 체육복을 가지고 있는 학생이 도둑맞은 경우
for (int i = 1; i <= n; i++) {
if (hasExtra[i] && isLost[i]) {
hasExtra[i] = false;
isLost[i] = false;
answer++;
}
}
for (int i = 1; i <= n; i++) {
if (isLost[i]) {
// 앞 번호한테 빌리기
if (i > 1 && hasExtra[i - 1]) {
hasExtra[i - 1] = false;
isLost[i] = false;
answer++;
continue;
}
// 뒷 번호한테 빌리기
if (i < n && hasExtra[i + 1]) {
hasExtra[i + 1] = false;
isLost[i] = false;
answer++;
}
}
}
return answer;
}
}
다른 사람의 코드
class Solution {
public int solution(int n, int[] lost, int[] reserve) {
int[] people = new int[n]; // 0: normal, -1: lost, 1: reserve >> 내 코드의 boolean 배열 2개를 대체
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;
}
}
Share article