算法刷題細節點總結
1. 關於比較器Comparator
Queue<Integer> pq=new PriorityQueue<Integer>(new Comparator<Integer>(){
public int compare(Integer a, Integer b){ // 這裏要嚴格寫成和上面的一樣
return b-a;
}
});
原來上面的compare方法中參數類型寫成了 int, 以為也能編譯通過,結果不行,要嚴格和Comparator中的泛型一致。自定義了比較器後就可以在Collections和Arrays的sort方法對容器中的元素進行排序,默認是升序排序的。
2. 關於集合
(1) 如何遍歷map?
可以參考這篇博文:https://www.cnblogs.com/imzhj/p/5981665.html
感覺最好記的方法是這個:
Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
entry.getKey();
entry.getValue();
}
(2) set集合的增刪改元素方法和List集合是一樣的嗎?remove方法的一個疑問
一樣的,都是 add 和 remove 方法,只不過list的remove方法能按照indxex來刪,而set只能按照Object來刪。這裏有一個長久以來的疑問是如果List集合中放入的是int型元素的話,如果此時使用remove方法,傳入int的 話是按照索引來刪除元素還是按照int的值來刪除元素的呢?
測試結果是還是按照索引來刪,如果使用 (Integer)3 這種方式將int包裝為Integer的話就會按照值去刪。
(3) set和list集合怎麽和數組互轉?
參考: https://blog.csdn.net/my_precious/article/details/53010232
(4) 關於PriorityQueue的用法
參考:https://blog.csdn.net/u013309870/article/details/71189189
很有用的數據結構,可以用它來實現堆。
3. 關於字符和字符串
(1) 相互轉換
int轉String直接加""即可,String轉int需要用到Integer.parseInt()方法。
String轉char數組直接調用toCharArray()方法,
(2) 快速逆轉字符串
String reversed = new StringBuilder(s).reverse().toString()
算法刷題細節點總結