1. 문제 풀이 아이디어
Set
자료구조를 활용해 효율적으로 문제를 해결할 수 있다.
2. 나의 정답 코드
class Solution {
public int solution(int n, int[] lost, int[] reserve) {
Set<Integer> lostSet = new HashSet<>();
Set<Integer> reserveSet = new HashSet<>();
for (int l : lost) {
lostSet.add(l);
}
for (int r : reserve) {
if (lostSet.contains(r)) {
lostSet.remove(r);
} else {
reserveSet.add(r);
}
}
int count = 0;
for (int l : lostSet) {
if (reserveSet.contains(l - 1)) {
reserveSet.remove(l - 1);
count++;
} else if (reserveSet.contains(l + 1)) {
reserveSet.remove(l + 1);
count++;
}
}
return n - lostSet.size() + count;
}
}
3. 정리
- 잃어버린 학생 번호와 여벌이 있는 학생 번호를 저장할
lostSet
과reserveSet
을 정의한다.
lost
배열을 순회하며lostSet
에 학생 번호를 추가한다.
reserve
배열을 순회하며reserveSet
에 학생 번호를 추가하되,lostSet
에 포함된 번호라면lostSet
에서 제거한다.
lostSet
을 순회하며,l-1
또는l+1
이reserveSet
에 존재하면 해당 번호를reserveSet
에서 제거하고count
를 증가시킨다.
- 마지막으로, 전체 학생 수
n
에서lostSet
의 크기를 뺀 후count
를 더해 최종 결과를 반환한다.
Share article