Java Tree Map


  • 0
    G
    class LogSystem {
    
        private TreeMap<String, Integer> cache;
        
        public LogSystem() {
            cache = new TreeMap<>();
        }
        
        public void put(int id, String timestamp) {
            cache.put(timestamp, id);
        }
        
        public List<Integer> retrieve(String s, String e, String gra) {
            List<Integer> result = new ArrayList<>();
            s = getKeyAccToGran(s, gra, true);
            e = getKeyAccToGran(e, gra, false);
            for(Map.Entry<String, Integer> entry : cache.tailMap(s).entrySet()){
                if(entry.getKey().compareTo(e) > 0) break;
                result.add(entry.getValue());
            }
            return result;
        }
        
        private String getKeyAccToGran(String key, String gran, boolean isStart){
            String [] tokens = key.split(":");
            String [] emptTokens;
            if(isStart) emptTokens = new String[]{"0000", "00", "00", "00", "00", "00"};
            else emptTokens = new String[]{"9999", "12", "31", "23", "59", "59"};
            if(gran.equals("Year")) return tokens[0] + ":" + joinStringTokens(":", Arrays.copyOfRange(emptTokens, 1, 6));
            if(gran.equals("Month")) return joinStringTokens(":", Arrays.copyOfRange(tokens, 0, 2)) + ":" + joinStringTokens(":", Arrays.copyOfRange(emptTokens, 2, 6));
            if(gran.equals("Day")) return joinStringTokens(":", Arrays.copyOfRange(tokens, 0, 3)) + ":" + joinStringTokens(":", Arrays.copyOfRange(emptTokens, 3, 6));
            if(gran.equals("Hour")) return joinStringTokens(":", Arrays.copyOfRange(tokens, 0, 4)) + ":" + joinStringTokens(":", Arrays.copyOfRange(emptTokens, 4, 6));
            if(gran.equals("Minute")) return joinStringTokens(":", Arrays.copyOfRange(tokens, 0, 5)) + ":" + joinStringTokens(":", Arrays.copyOfRange(emptTokens, 5, 6));
            return key;
        }
        
        private String joinStringTokens(String del, String[] tokens){
            StringBuilder sb = new StringBuilder();
            for(int i = 0 ; i < tokens.length ; ++i){
                sb.append(tokens[i]);
                if(i != tokens.length - 1){
                    sb.append(del);
                }
            }
            return sb.toString();
        }
    }
    
    /**
     * Your LogSystem object will be instantiated and called as such:
     * LogSystem obj = new LogSystem();
     * obj.put(id,timestamp);
     * List<Integer> param_2 = obj.retrieve(s,e,gra);
     */
    

Log in to reply
 

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