inblog logo
|
LHS's Study Space
    알고리즘문제풀기프로그래머스

    [프로그래머스] 체육복(42862)

    lhs's avatar
    lhs
    Dec 12, 2024
    [프로그래머스] 체육복(42862)
    Contents
    1. 문제 풀이 아이디어2. 나의 정답 코드3. 정리
    school.programmers.co.kr
    https://school.programmers.co.kr/learn/courses/30/lessons/42862
     

    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
    Contents
    1. 문제 풀이 아이디어2. 나의 정답 코드3. 정리

    LHS's Study Space

    RSS·Powered by Inblog