Straight forward C++ multimap solution


  • 2
    A
    class LogSystem {
    private:
        multimap<string, int> m;
        
    public:
        LogSystem() {
            
        }
        
        void put(int id, string timestamp) {
            m.emplace(timestamp, id);
        }
        
        vector<int> retrieve(string s, string e, string gra) {
            if (gra == "Year") {
                s = s.substr(0, 4) + ":01:01:00:00:00";
                e = e.substr(0, 4) + ":12:31:23:59:59";
            }
            else if (gra == "Month") {
                s = s.substr(0, 7) + ":01:00:00:00";
                e = e.substr(0, 7) + ":31:23:59:59";
            }
            else if (gra == "Day") {
                s = s.substr(0, 10) + ":00:00:00";
                e = e.substr(0, 10) + ":23:59:59";
            }
            else if (gra == "Hour") {
                s = s.substr(0, 13) + ":00:00";
                e = e.substr(0, 13) + ":59:59";
            }
            else if (gra == "Minute") {
                s = s.substr(0, 16) + ":00";
                e = e.substr(0, 16) + ":59";
            }
            auto start = m.lower_bound(s), end = m.upper_bound(e);
            vector<int> ans;
            for (auto iter = start; iter != end; ++iter)
                ans.push_back(iter->second);
            return ans;
        }
    };
    

  • 4
    I

    Good idea to sort the timestamps. It scales better than only using list. As an improvement to coding (not efficiency), we can do:

    class LogSystem {
    private:
        multimap<string, int> log;
        string low = "2000:00:00:00:00:00";
        string high = "2017:12:31:23:59:59";
        unordered_map<string, int> map = {{"Year", 4}, {"Month", 7}, {"Day", 10},
                                          {"Hour", 13}, {"Minute", 16}, {"Second", 19}};
    
    public:
        LogSystem() {
            
        }
        
        void put(int id, string timestamp) {
            log.emplace(timestamp, id);
        }
        
        vector<int> retrieve(string s, string e, string gra) {
            int len = map[gra];
            s = s.substr(0, len) + low.substr(len);
            e = e.substr(0, len) + high.substr(len);
            auto first = log.lower_bound(s);
            auto last = log.upper_bound(e);
            vector<int> result;
            for (auto it = first; it != last; it++)
                result.push_back(it->second);
            return result;
        }
    };
    

  • 0
    H

    good!good!good!


  • -1
    H

    @Aeonaxx The problem states "Unique timestamp", so a map is sufficient.


Log in to reply
 

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