상세 컨텐츠

본문 제목

[프로그래머스] 롤케이크

💯ProblemSolving/문제 풀이-Java

by :부셔져버린개발자 2025. 2. 3. 12:14

본문

       문제 요약        

- 문제

https://school.programmers.co.kr/learn/courses/30/lessons/132265

 

 

         아이디어        

왼쪽 계속 증가 오른쪽 계속 감소

오른쪽에 모두 넣어둔 뒤 오른쪽은 감소시키고, 왼쪽에 증가시킴

 

 

         소스코드        

import java.util.*;
class Solution {
    public int solution(int[] topping) {
        int answer = 0;
        // i번째 인덱스까지 토핑의 개수
        // left는 같거나 증가하므로 
        Map<Integer, Integer> cake1 = new HashMap<>();
        Map<Integer, Integer> cake2 = new HashMap<>();
        for(int i = 0; i < topping.length; i++) {
            cake2.put(topping[i], cake2.getOrDefault(topping[i],0) + 1);
        }
        
        for(int i = 0; i < topping.length; i++) {
            cake1.put(topping[i], cake1.getOrDefault(topping[i], 0) + 1);
            
            if(cake2.getOrDefault(topping[i], 0) - 1 >0){
                cake2.put(topping[i], cake2.getOrDefault(topping[i], 0) - 1);
            }else {
                cake2.remove(topping[i]);
            }
            
            if(cake1.keySet().size() == cake2.size()) {
                answer += 1;
            }
        }
        
        return answer;
    }
}

 

 

728x90

관련글 더보기