1. java中的PriorityQueue允许自定义comparator来定义PriorityQueue中的元素是按怎样的规则排序 插入到heap中的。
用法:
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;
}
});
两个参数:capacity (pq的初始大小), comparator.
PriorityQueue添加元素: add(o) or offer(o); 区别: add()来自Collections, offer()来自Queue, 若queue的capacity事先指定,则add()永远返回true, 但offer()可能返回false,表示无法添加此元素。在priorityQueue中,两个方法同义。
poll() :Retrieves and removes the head of this queue, or returns null if this queue is empty.
Removes a single instance of the specified element from this queue, if it is present.
|
poll()
peek()
总结起来,添加元素用offer(o), 删除队头元素用poll(), 查看队头元素但不删除用peek()
2. 有时需要将array中的元素全部加到ArrayList中,通过??
或者将List中的元素全部加到Set中,在创建set的时候把要复制的list作为参数。
Set<String> wordSet = new HashSet<>(wordDict);
3. 遍历Hashmap:
Map<Integer, Integer> map = new HashMap<>();
map.put(1,2);
//iterate over entries
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<Integer, Integer> entry = (Map.Entry)iter.next();
int key = entry.getKey();
int val = entry.getValue();
}
//iterate over keys
Iterator keyIter = map.keySet().iterator();
// iterate over values
Iterator valIter = map.valueSet().iterator();