Fast Java Solution using List<String[]> and HashMap


  • 0
    S
    public class LogSystem {
        List<String[]> logs;
        Map<String, Integer> indices;
        public LogSystem() {
            logs = new ArrayList<String[]>();
            indices = new HashMap<String, Integer>();
            indices.put("Year", 4);
            indices.put("Month", 7);
            indices.put("Day", 10);
            indices.put("Hour", 13);
            indices.put("Minute", 16);
            indices.put("Second", 19);
        }
        
        public void put(int id, String timestamp) {
            logs.add(new String[]{String.valueOf(id), timestamp});
        }
        
        public List<Integer> retrieve(String s, String e, String gra) {
            List<Integer> result = new ArrayList<>();
            int idx = indices.get(gra);
            for (String[] log : logs) {
                String timestamp = log[1];
                if (timestamp.substring(0, idx).compareTo(s.substring(0, idx)) >= 0 &&
                    timestamp.substring(0, idx).compareTo(e.substring(0, idx)) <= 0) {
                    result.add(Integer.valueOf(log[0]));
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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