[Short] 5 lines C++ using static map


  • 1
        vector<int> lexicalOrder(int n) {
            vector<int>res;
            static map<string, int>m;
            if(n > m.size()) for(int i = m.size() + 1; i < n + 1; i++) m[to_string(i)] = i;
            for(auto x: m) if(x.second < n + 1) res.push_back(x.second);
            return res;
        }
    

  • 0
    J

    This is a elegant solution.
    Why do you make the map static? Could you explain?


  • 0

    @JoeAtWork A static map can maintain it's content through all test cases, so suppose the first input n = 5,000,000 (max size of input), you won't need to fill the map in the following TCs, you just read the data from static map.


Log in to reply
 

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