优先队列

以后同步到csdn中

以下写在https://blog.csdn.net/ycllycll/article/details/102238286中

leetcode322  用BFS 动态规划两种解法写在 279 下面(他们两思想一样)

127. Word Ladder(也是转化为无权图的最短路径-bfs)

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWord is nota transformed word.
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output: 5

Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

代码如下:
public class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        Set<String> dict = new HashSet<>(wordList);
        Set<String> vis = new HashSet<>();
        Queue<String> q = new LinkedList<>();
        q.offer(beginWord);
        for (int len = 1; !q.isEmpty(); len++) {
            for (int i = q.size(); i > 0; i--) {
                String w = q.poll();
                if (w.equals(endWord)) return len;

                for (int j = 0; j < w.length(); j++) {
                    char[] ch = w.toCharArray();
                    for (char c = 'a'; c <= 'z'; c++) {
                        if (c == w.charAt(j)) continue;
                        ch[j] = c;
                        String nb = String.valueOf(ch);
                        if (dict.contains(nb) && vis.add(nb)) q.offer(nb);
                    }
                }
            }
        }
        return 0;
    }
}
126. Word Ladder II  比较难


一、优先队列
java的PriorityQueue默认是一个最小堆。
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(); //小顶堆,默认容量为11
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(11,new Comparator<Integer>(){ //大顶堆,容量11
    @Override
    public int compare(Integer i1,Integer i2){
        return i2-i1;
    }
});

347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]
 1 //方法一 use maxHeap. Put entry into maxHeap so we can always poll a number with largest frequency
 2 public class Solution {
 3     public List<Integer> topKFrequent(int[] nums, int k) {
 4         Map<Integer, Integer> map = new HashMap<>();
 5         for(int n: nums){
 6             map.put(n, map.getOrDefault(n,0)+1);
 7         }
 8            
 9         PriorityQueue<Map.Entry<Integer, Integer>> maxHeap = 
10                          new PriorityQueue<>((a,b)->(b.getValue()-a.getValue()));//安对象的value来建立大顶堆
11         for(Map.Entry<Integer,Integer> entry: map.entrySet()){
12             maxHeap.add(entry);
13         }
14         
15         List<Integer> res = new ArrayList<>();
16         while(res.size()<k){
17             Map.Entry<Integer, Integer> entry = maxHeap.poll();
18             res.add(entry.getKey());
19         }
20         return res;
21     }
22 }
23 
24 
25 
26 
27 
28 //方法二 桶排序
29 public List<Integer> topKFrequent(int[] nums, int k) {
30 
31     List<Integer>[] bucket = new List[nums.length + 1];
32     Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();
33 
34     for (int n : nums) {
35         frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
36     }
37 
38     for (int key : frequencyMap.keySet()) {
39         int frequency = frequencyMap.get(key);
40         if (bucket[frequency] == null) {
41             bucket[frequency] = new ArrayList<>();
42         }
43         bucket[frequency].add(key);
44     }
45 
46     List<Integer> res = new ArrayList<>();
47 
48     for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {
49         if (bucket[pos] != null) {
50             res.addAll(bucket[pos]);
51         }
52     }
53     return res;
54 }
23. Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

代码如下:
//使用优先队列
public
class Solution { public ListNode mergeKLists(List<ListNode> lists) { if (lists==null||lists.size()==0) return null; PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){ @Override public int compare(ListNode o1,ListNode o2){ if (o1.val<o2.val) return -1; else if (o1.val==o2.val) return 0; else return 1; } }); ListNode dummy = new ListNode(0); ListNode tail=dummy; for (ListNode node:lists) if (node!=null) queue.add(node); while (!queue.isEmpty()){ tail.next=queue.poll(); tail=tail.next; if (tail.next!=null) queue.add(tail.next); } return dummy.next; } }

//也可以使用归并排序






















原文地址:https://www.cnblogs.com/yangcao/p/11651047.html