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;
}
}
로직이 무척 간단하다! 🤓
학생의 수를 크기로 갖는 people 배열을 하나 생성 후
lost 배열에 있는 학생은 -1
reserve 배열에 있는 학생은 +1
그리고 옷을 잃어버린 학생에게 옷을 빌려줄 수 있는지를 확인하기 위해
반복문을 돌려 people 배열을 탐색한다.
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--;
import java.util.Arrays;
class Solution {
public int solution(int n, int[] lost, int[] reserve) {
int answer = n - lost.length;
// 여벌옷이 있는 학생이 도난당한 경우 체크
for (int i = 0; i < reserve.length; i++) {
for (int j = 0; j < lost.length; j++) {
if (reserve[i] == lost[j]) {
reserve[i] = -1;
lost[j] = -1;
answer++;
break;
}
}
}
// 옷 확인
for (int i = 0; i < reserve.length; i++) {
if (reserve[i] == -1) continue;
for (int j = 0; j < lost.length; j++) {
if (lost[j] == -1) continue;
if (Math.abs(reserve[i] - lost[j]) == 1) {
lost[j] = -1;
answer++;
break;
}
}
}
return answer;
}
}
🤔
처음 풀어본 날: 23.03.28
학습한 날 : 23.03.29 ~ 30