문제 설명
https://school.programmers.co.kr/learn/courses/30/lessons/42862

제한 사항

입출력 예

풀이
import java.util.ArrayList;
import java.util.Arrays;
class Solution {
public int solution(int n, int[] lost, int[] reserve) {
ArrayList<Integer> lostList = new ArrayList<>();
Arrays.sort(reserve);
for (int i : lost) lostList.add(i);
for (int i = 0; i < reserve.length; i++) {
if (lostList.contains(reserve[i])) {
lostList.remove(lostList.indexOf(reserve[i]));
reserve[i] = 0;
}
}
for (int i = 0; i < reserve.length; i++) {
if (reserve[i] == 0) continue;
if (lostList.contains(reserve[i] - 1))
lostList.remove(lostList.indexOf(reserve[i] - 1));
else if (lostList.contains(reserve[i] + 1))
lostList.remove(lostList.indexOf(reserve[i] + 1));
}
return n - lostList.size();
}
}
후기
일단 카테고리부터 그리디로 설정되어 있다. 힌트가 대놓고;; 풀이법은 간단하다. 1번부터 순서대로 줄지어 놓고 여분 체육복을 가지고 있는 사람이 있으면 자신의 앞 번호가 체육복을 도난당했다 하면 그 사람에게 주고 아니면 다음 사람을 확인하고 도난당했으면 그 사람에게 주면 된다. 번호 순서대로 확인한다는 조건을 임의로 집어 넣어 이미 지나온 번호의 도난 당한 체육복은 줄 수가 없게 만든 것이다. 그때그때마다 최선의 선택을 하게되는 것이다.
'코딩테스트 (프로그래머스) > Java' 카테고리의 다른 글
| [프로그래머스][JAVA][Lv. 1] 모의고사 (0) | 2023.07.17 |
|---|---|
| [프로그래머스][JAVA][Lv. 2] 두 원 사이의 정수 쌍 (0) | 2023.07.17 |
| [프로그래머스][JAVA][Lv. 1] 실패율 (0) | 2023.07.16 |
| [프로그래머스][JAVA][Lv. 1] 3진법 뒤집기 (0) | 2023.07.15 |
| [프로그래머스][JAVA][Lv. 1] 키패드 누르기 (0) | 2023.07.14 |