JAVA using TreeMap easy to understand


  • 0
    6

    Just create two bounds and find them in the TreeMap.

    public class LogSystem {
        TreeMap<String, List<Integer>> map;
        Map<String, Integer> dic;
        static final String[][] record = {{"2017", "2000"}, {"12", "01"}, {"31", "01"}, {"23", "00"}, {"59", "00"},{"59","00"}};
        
        public LogSystem() {
            map = new TreeMap<>();
            dic = new HashMap<>();
            dic.put("Year", 0);
            dic.put("Month", 1);
            dic.put("Day", 2);
            dic.put("Hour", 3);
            dic.put("Minute", 4);
            dic.put("Second", 5);
        }
        
        public void put(int id, String timestamp) {
            if(!map.containsKey(timestamp))
                map.put(timestamp, new ArrayList<>());
            map.get(timestamp).add(id);
        }
        
        public List<Integer> retrieve(String s, String e, String gra) {
            String upper = getBound(e, gra, true);
            String lower = getBound(s, gra, false);
            List<Integer> list = new ArrayList<>();
            String start = map.ceilingKey(lower);
            while(start!=null && start.compareTo(upper) <= 0){
                list.addAll(map.get(start));
                start = map.higherKey(start);
            }
            return list;
        }
        
        public String getBound(String s, String gra, boolean isUpper){
            int b = isUpper ? 0 : 1;
            int g = dic.get(gra);
            StringBuilder sb = new StringBuilder();
            String[] ss = s.split(":");
            int i = 0;
            for(;i <= g; i++){
                sb.append(ss[i]).append(":");
            }
            for(; i < 6; ++i)
                sb.append(record[i][b]).append(":");
            return sb.deleteCharAt(sb.length()-1).toString();
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.