首先,集合的有序无序是指在插入的时候,保持插入的顺序性,先插入的放在集合前面,后插入的放在集合后面。
而排序是指插入元素后,集合中的元素是否自动进行排序(例如升序降序)。
实现List接口的,例如ArrayList,LinkedList都是有序的
实现Set接口的,例如HashSet,TreeSet,LinkHashSet等都是无序的,但是TreeSet是基于树排序的。
实现Map接口的,例如HashMap,HashTable,
LinkedHashMap,TreeMap也都是无序的,但是TreeMap是基于树排序的。
class MyCalendarThree {
private TreeMap<Integer, Integer> cnt;
public MyCalendarThree() {
cnt = new TreeMap<Integer, Integer>();
}
public int book(int start, int end) {
int ans = 0;
int maxBook = 0;
cnt.put(start, cnt.getOrDefault(start, 0) + 1);
cnt.put(end, cnt.getOrDefault(end, 0) - 1);
for (Map.Entry<Integer, Integer> entry : cnt.entrySet()) {
maxBook += freq;
ans = Math.max(maxBook, ans);
}
return ans;
}
}
class FreqStack {
Map<Integer, Stack<Integer>> freqStkMap;
Map<Integer, Integer> numFreqMap;
int maxFreq;
public FreqStack() {
freqStkMap = new HashMap<>();
numFreqMap = new HashMap<>();
maxFreq = 0;
}
public void push(int val) {
int currFreq = numFreqMap.getOrDefault(val,0)+1;
numFreqMap.put(val,currFreq);
if(currFreq>maxFreq){
maxFreq=currFreq;
}
freqStkMap.putIfAbsent(currFreq, new Stack<>());
freqStkMap.get(currFreq).push(val);
}
public int pop() {
int maxFreqNum = freqStkMap.get(maxFreq).pop();
numFreqMap.put(maxFreqNum, numFreqMap.get(maxFreqNum) - 1);
if(freqStkMap.get(maxFreq).size() == 0){
maxFreq--;
}
return maxFreqNum;
}
}
/**
* Your FreqStack object will be instantiated and called as such:
* FreqStack obj = new FreqStack();
* obj.push(val);
* int param_2 = obj.pop();
*/
class SummaryRanges {
TreeMap<Integer,Integer> treeMap;
public SummaryRanges() {
treeMap = new TreeMap<>();
}
public void addNum(int val) {
Integer l =treeMap.floorKey(val);
if(l!= null && l<=val && treeMap.get(l)>=val){
return;
}
Integer r =treeMap.ceilingKey(val);
if(r!=null && r==val+1){
treeMap.put(val, treeMap.get(r));
treeMap.remove(r);
} else {
treeMap.put(val,val);
}
if(l!=null && treeMap.get(l) == val-1){
treeMap.put(l,treeMap.get(val));
treeMap.remove(val);
}
}
public int[][] getIntervals() {
int[][] ans = new int[treeMap.size()][2];
int idx=0;
for(Map.Entry<Integer,Integer> entry: treeMap.entrySet()){
ans[idx][0] = entry.getKey();
ans[idx++][1] = entry.getValue();
}
return ans;
}
}
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges obj = new SummaryRanges();
* obj.addNum(val);
* int[][] param_2 = obj.getIntervals();
*/
getOrDefault(Object key, V defaultValue)
意思就是当Map集合中有这个key时,就使用这个key对应的value值,如果没有就使用默认值defaultValue