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