import java.util.HashMap;
public class Solution {
// 롤케이크 자르기
public static int solution(int[] topping) {
int answer = 0;
HashMap<Integer, Integer> hm1 = new HashMap<>();
HashMap<Integer, Integer> hm2 = new HashMap<>();
for (int i = 0; i < topping.length; i++) {
hm2.put(topping[i], hm2.getOrDefault(topping[i], 0) + 1);
}
// hm2 : {1=4, 2=2, 3=1, 4=1}
for (int i = 0; i < topping.length; i++) {
hm1.put(topping[i], hm1.getOrDefault(topping[i], 0) + 1);
if (hm2.containsKey(topping[i])) {
hm2.put(topping[i], hm2.get(topping[i]) - 1);
}
if (hm2.get(topping[i]) == 0) {
hm2.remove(topping[i]);
}
if (hm1.size() == hm2.size()) { // hm1 : {1=2, 2=1, 3=1}, hm2 : {1=2, 2=1, 4=1} // hm1 : {1=3, 2=1, 3=1}, hm2 : {1=1, 2=1, 4=1}
answer++;
}
}
return answer;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] topping = {1, 2, 1, 3, 1, 4, 1, 2}; // 1, 2, 1, 3과 1, 4, 1, 2로 잘랐을 떄, 1, 2, 1, 3, 1과 4, 1, 2로 잘랐을 때
System.out.println(solution(topping)); // 2
}
}
프로그래머스 롤케이크 자르기 문제 풀이 Java
'Java > 프로그래머스' 카테고리의 다른 글
[Java] 프로그래머스 [Level-4] 쌍둥이 빌딩 숲 (0) | 2022.12.06 |
---|---|
[Java] 프로그래머스 [Level-3] 순위 (0) | 2022.11.29 |
[Java] 프로그래머스 [Level-3] 양과 늑대 (0) | 2022.11.29 |
[Java] 프로그래머스 [Level-3] 아이템 줍기 (0) | 2022.11.29 |
[Java] 프로그래머스 [Level-2] 피로도 (0) | 2022.11.29 |