题目描述
Leetcode 653: 设计一个log system,实现两个问询,一个插入一个[ID, Timestamp]的log,一个给出起始和终止点返回所有Timestamp在其中的log-ID(以时间升序的方式)。
题目思路
1. 暴力求解
建立一个List来保存所有的log对象,然后查找log时,遍历所有List中的数据,将符合条件的返回到一个新的List中然后,对这个List以TimeStamp排序返回。优点是插入可以,缺点是每一次查找log时需要进行排序返回,大大降低了效率
。
2. 平衡二叉树
介于上面思路的缺点,能不能建立一个数据结构使数据在插入的时候就能保持有序,二叉搜索树BST就可以实现,为了保证二叉搜索树查询复杂度在,需要维护BST的平衡性。这样查询操作只需要遍历一边log system即可。Java中TreeMap实现的就是平衡二叉树,代码如下:
class LogSystem {
// 插入及有序 logN 平衡二叉树求解 - TreeMap
TreeMap<String, Integer> logs;
// mapping 截取
HashMap<String, Integer> gran = new HashMap<>();
public LogSystem() {
logs = new TreeMap<>();
gran.put("Year", 4);
gran.put("Month",7);
gran.put("Day", 10);
gran.put("Hour", 13);
gran.put("Minute", 16);
gran.put("Second", 19);
}
public void put(int id, String timestamp) {
logs.put(timestamp, id);
}
public List<Integer> retrieve(String start, String end, String granularity) {
// 先序遍历所有的key 然后return满足条件的
int cut = gran.get(granularity);
String st = start.substring(0, cut);
String ed = end.substring(0, cut);
List<Integer> res = new ArrayList<>();
for(String t: logs.keySet()) {
String t1 = t.substring(0, cut);
if(t1.compareTo(st)>=0 && t1.compareTo(ed)<=0) res.add(logs.get(t));
}
return res;
}
}
/**
* Your LogSystem object will be instantiated and called as such:
* LogSystem obj = new LogSystem();
* obj.put(id,timestamp);
* List<Integer> param_2 = obj.retrieve(start,end,granularity);
*/
时间复杂度:;空间复杂度:
。
3. 平衡二叉树 + 二分查找
在查询功能上我们还可以通过二分查找进行优化,二分查找得到起始和终止log的位置,然后将起始和终止之间所有log返回即可,省去很多多余的遍历。
时间复杂度:;空间复杂度:
。