C++ easy to understand solution


  • 2
    D
    class LogSystem {
    public:
        unordered_map<string, int> mp;
        unordered_map<string, int> mapping;
    
        LogSystem() {
            mapping["Year"] = 0;
            mapping["Month"] = 1;
            mapping["Day"] = 2;
            mapping["Hour"] = 3;
            mapping["Minute"] = 4;
            mapping["Second"] = 5;
        }
        
        void put(int id, string timestamp) {
            mp[timestamp] = id;   
        }
        
        vector<int> retrieve(string s, string e, string gra) {
            vector<int> result;
            for (auto p : mp) {
                string tp = p.first;
                if (bigger(tp, s, gra) && smaller(tp, e, gra)) result.push_back(p.second);
            }
            return result;
        }
        bool smaller(string t1, string t2, string grad) {
            auto w1 = split(t1);
            auto w2 = split(t2);
            for (int i = 0; i <= mapping[grad]; i++) {
                if (w1[i] > w2[i]) return false;
                else if (w1[i] < w2[i]) return true;
            }
            return true;
        }
        
        bool bigger(string t1, string t2, string grad) {
            auto w1 = split(t1);
            auto w2 = split(t2);
            for (int i = 0; i <= mapping[grad]; i++) {
                if (w1[i] < w2[i]) return false;
                else if (w1[i] > w2[i]) return true;
            }
            return true;
        }
        
        vector<int> split(string t) {
            vector<int> words;
            istringstream iss(t);
            string s;
            while (getline(iss, s, ':')) {
                words.push_back(stoi(s));
            }
            return words;
        }
    };
    
    /**
     * Your LogSystem object will be instantiated and called as such:
     * LogSystem obj = new LogSystem();
     * obj.put(id,timestamp);
     * vector<int> param_2 = obj.retrieve(s,e,gra);
     */
    

  • 0
    G

    Hi, your code has bugs, store a timestamp-->id mapping is not a good idea. The description doesn't say that two logs must have different timestamp, so they can be the same. For the following test cases:

    ["LogSystem","put","put","put","put","retrieve","retrieve"]
    [[],[1,"2017:01:01:23:59:59"],[2,"2017:01:01:23:59:59"],[3,"2017:01:01:22:59:59"],[4,"2016:01:01:00:00:00"],["2016:01:01:01:01:01","2017:01:01:23:00:00","Year"],["2016:01:01:01:01:01","2017:01:01:23:00:00","Hour"]]

    Your code is returning [null,null,null,null,null,[4,3,2],[3,2]], and expected answer is [null,null,null,null,null,[4,3,1,2],[3,1,2]], obviously OJ doesn't catch this.


  • 0
    D

    the problem states "Given a log's unique id and timestamp". Suppose the timestamp is not unique, you can easily solve that by using id as key.


Log in to reply
 

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