코딩테스트 연습 - 롤케이크 자르기 | 프로그래머스 스쿨 (programmers.co.kr)
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
조각마다 동일한 가짓수의 토핑이 올라가 있으면 공평하게 나누어진 것이다.
→ 토핑의 개수보다는 가짓수가 중요하다.
롤 케이크를 공평하게 자르는 방법의 수를 구하시오.
전체 토핑을 관리하며 포인트를 이동시켜 가며 확인을 한다.
- 토핑 종류 : 개수 Map으로 기록
- 포인터를 0부터 오른쪽으로 이동시켜한다.
- 해당 포인터의 토핑을 Map 에서 1개 뺀다. 만약 개수가 0이 되면 제거한다.
- 현재 내 토핑은 Set을 통해 관리한다.
- 최종적으로 내 토핑 set과 전체 토핑 map의 크기가 같으면 공평한 것이다.
import java.util.*;
class Solution {
public int solution(int[] topping) {
Map<Integer, Integer> toppings = new HashMap<>();
Set<Integer> myToppings = new HashSet<>();
int answer = 0;
for (int t : topping) {
toppings.put(t, toppings.getOrDefault(t, 0) + 1);
}
for (int i = 0; i < topping.length; i++) {
int t = topping[i];
myToppings.add(t);
toppings.put(t, toppings.get(t) - 1);
if (toppings.get(t) == 0) {
toppings.remove(t);
}
if (myToppings.size() == toppings.size()) {
answer++;
}
}
return answer;
}
}
'Algorithm > Programmers' 카테고리의 다른 글
Programmers 42897 - 도둑질 (0) | 2024.10.30 |
---|---|
BOJ 2295 - 세 수의 합 (0) | 2024.10.26 |
Programmers 42577 - 전화번호 목록 (0) | 2024.10.24 |
Programmers 62050 - 지형 이동 (0) | 2024.10.23 |
Programmers 64065 - 튜플 (3) | 2024.10.23 |