728x90
https://school.programmers.co.kr/learn/courses/30/lessons/42862
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
728x90
메모리: 84.9 MB, 시간: 0.53 ms
사용 알고리즘: 그리디 알고리즘
import java.util.*;
class Solution {
public int solution(int n, int[] lost, int[] reserve) {
// 체육복을 도난 당하지 않은 학생 수
int answer = n - lost.length;
// 체육복 잃어버린 학생 배열
boolean[] isLost = new boolean[n + 2]; // 앞뒤로 마진 주기
for(int l : lost) isLost[l] = true;
// 여벌의 체육복을 가져온 학생 배열 정렬
Arrays.sort(reserve);
// 본인도 잃어버려 체육복을 빌려줄 수 없는 학생 배열
boolean[] cantLend = new boolean[reserve.length];
for(int i = 0; i < reserve.length; i++) {
if(isLost[reserve[i]]) {
isLost[reserve[i]] = false;
answer++;
cantLend[i] = true;
}
}
// 체육복 빌려주기
int r;
for(int i = 0; i < reserve.length; i++) {
// 본인이 잃어버렸으면 빌려줄 수 없음
if(cantLend[i]) continue;
r = reserve[i];
// 앞 사람 빌려주기
if(isLost[r - 1]) {
isLost[r - 1] = false;
answer++;
}
// 뒷 사람 빌려주기
else if(isLost[r + 1]) {
isLost[r + 1] = false;
answer++;
}
}
return answer;
}
}
728x90
'Problem Solving > Programmers' 카테고리의 다른 글
[프로그래머스, 181867] x 사이의 개수 (java) (0) | 2025.03.06 |
---|---|
[프로그래머스, 120861] 캐릭터의 좌표 (java) (0) | 2025.03.06 |
[프로그래머스, 181925] 수 조작하기 2 (java) (0) | 2025.03.05 |
[프로그래머스, 181868] 공백으로 구분하기 2 (java) (0) | 2025.02.20 |
[프로그래머스, 181869] 공백으로 구분하기 1 (java) (0) | 2025.02.20 |