692 Top K Frequent Words

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> hash = new HashMap<>();
        for (String word : words){
            if (!hash.containsKey(word)){
                hash.put(word, 1);
            }
            else{
                hash.put(word, hash.get(word) + 1);
            }
        }

        PriorityQueue<String> q = new PriorityQueue<>((a, b) -> {
            return hash.get(a) != hash.get(b) ? hash.get(a) - hash.get(b) : b.compareTo(a);
        });

        for (String word : hash.keySet()){
            q.offer(word);
            if (q.size() > k) q.poll();
        }

        List<String> ans = new ArrayList<>();
        while (!q.isEmpty()) ans.add(q.poll());

        Collections.reverse(ans);
        return ans;
    }
}

373 Find K Pairs with Smallest Sums

class Solution {
    public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        PriorityQueue<int[]> q = new PriorityQueue<int[]>((a, b) -> (a[0] + a[1] - b[0] - b[1]));
        List<int[]> ans = new ArrayList<>();
        if(nums1.length==0 || nums2.length==0 || k==0) return ans;
        for (int i = 0; i < nums1.length && i < k; i++){
            q.offer(new int[]{nums1[i], nums2[0], 0});
        }


        while (k-- > 0 && !q.isEmpty()){
            int[] cur = q.poll();
            ans.add(new int[]{cur[0], cur[1]});
            if (cur[2] == nums2.length - 1) continue;
            q.offer(new int[]{cur[0], nums2[cur[2] + 1], cur[2] + 1});
        }

        return ans;
    }
}

621 Task Scheduler

class Solution {
    public int leastInterval(char[] tasks, int n) {
        if (tasks == null || tasks.length == 0) return 0;

        int[] hash = new int[26];
        for (char task : tasks){
            hash[task - 'A']++;
        }

        PriorityQueue<Integer> pq = new PriorityQueue<>(26, (a, b) -> (b - a));

        for (int h : hash){
            if (h > 0) pq.offer(h);
        }

        int time = 0;
        while (!pq.isEmpty()){
            int i = 0;
            List<Integer> list = new ArrayList<>();
            while (i <= n){
                if (!pq.isEmpty()){
                    if (pq.peek() > 1){
                        list.add(pq.poll() - 1);
                    }
                    else{
                        pq.poll();
                    }    
                }

                time++;
                i++;
                if (list.size() == 0 && pq.isEmpty()) break;
            }
            for (int item : list){
                pq.offer(item);
            }
        }

        return time;
    }
}

results matching ""

    No results matching ""