• Home

My Codegate

  • Home

프로그래머스 체육복 자바 문제풀이

2023/12/06 Posted by Codegate Java No Comments
프로그래머스 체육복 자바 문제풀이

문제 링크

문제 내용을 요약해보자면 체육복을 잃어버린 사람과 여분을 있는 사람을 확인해서, 최대한 많은 사람이 체육복을 얻게 되는 값을 반환해주면 되는데, 주의할 점은 체육복 여분이 있는 사람이 체육복이 없는 경우도 있기 때문에, 그 경우에는 남에게 체육복을 줄 수 없다.

import java.util.Arrays;
import java.util.LinkedList;
import java.util.stream.Collectors;

class Solution {
    public static int solution(int n, int[] lost, int[] reserve) {
        Arrays.sort(lost);
        LinkedList<Integer> reserveList = Arrays.stream(reserve)
                                    .boxed().collect(Collectors.toCollection(LinkedList::new));

        int answer = 0;

        for(int i = 0; i<lost.length; i++) {
            int index = i;
            if (reserveList.contains(lost[i])) {
                reserveList.removeIf(val -> val == lost[index]);
                lost[i] = -2;
                answer++;
            }
        }

        for(int i = 0; i<lost.length; i++) {
            int index = i;
            if(reserveList.contains(lost[i] - 1)) {
                reserveList.removeIf(val -> val == lost[index] - 1);
                answer++;
                continue;
            }
            if(reserveList.contains(lost[i] + 1)) {
                reserveList.removeIf(val -> val == lost[index] + 1);
                answer++;
            }
        }

        return n - lost.length + answer;
    }
}

문제를 풀어보자면 체육복이 없는 사람 배열을 정렬시킨 후, 여분의 체육복을 모두 List 안에 넣고 여분의 옷을 가져온 사람들이 체육복이 없는 경우를 모두 제외시켜 준 다음

체육복이 없는 사람들을 반복문으로 돌려주면서 여분의 옷을 가져와주면 되는데 왼쪽 먼저 가져와야 오른쪽 사람이 챙기지 못하는 경우를 피할 수 있다.

위 방법대로 진행해주면서 여분의 옷 준 횟수를 계산한 다음, 전체 학생 – 옷 잃어버린 사람 + 여분의 옷 준 케이스를 반환하면 끝이다.

No Comments
0

Leave a Reply Cancel Reply

Introduction

My Codegate

Latest Posts

  • Google Search Console API 연동방법
  • 인텔리제이 Gradle Dependency 최신 버전 보는 방법
  • Wallet-Tracker 개발일지
  • Moralis API 자바로 호출방법
  • IntelliJ Commit 후 Push 따로 하는 방법

Categories

  • My Project (4)
  • Java (42)
  • Algorithm (161)
    • Java (152)
    • Algorithm Knowledge (3)
    • Algorithm site usage (6)
  • Vue.js (1)
  • Spring (4)
  • Docker (2)
  • IntelliJ (20)
  • Uncategorized (7)

Recent Comments

  • Codegate on Hello world!
  • A WordPress Commenter on Hello world!

© 2025 — mycodegate.com

Prev Next