Java Clean Easy Solution


  • 0
    C
    public class Solution {
        public int leastInterval(char[] tasks, int n) {
    		Map<Character, Integer> map = new HashMap<Character, Integer>();
            for(char task : tasks) {
                map.put(task, map.getOrDefault(task,0) + 1);
            }
            
            int count = 0;
                
            PriorityQueue<Integer> pq = new PriorityQueue<Integer>((a,b)->b-a);
            for(char c : map.keySet()) {
                pq.offer(map.get(c));
            }
            
            while (!pq.isEmpty()) {
                List<Integer> list = new ArrayList<Integer>();
                int cnt = 0;
                for(int i=0; i<n+1; i++) {
                    if(!pq.isEmpty()) {
                        list.add(pq.poll()-1);
                        cnt ++;
                    }
                }
                
                for(int i=0; i<list.size(); i++) {
                    if(list.get(i) > 0) {
                        pq.offer(list.get(i));
                    }
                }
    			
                if(pq.isEmpty()) {
                    count += cnt;
                    break;
                }
                
                count += n + 1;
            }
            
            return count;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.