C++ simple map based NLogN


  • 0
    V
    class Solution {
    public:
        vector<string> findRelativeRanks(vector<int>& nums) {
            map<int, int, std::greater<int>> order;
            for (int i = 0; i < nums.size(); i++) {
                order.insert(pair<int, int>(nums[i], i));
            }
            
            vector<string> solution(nums.size(), "");
            int i = 1;
            for(auto itr = order.begin(); itr != order.end(); itr++, i++) {
                switch (i) {
                case 1:
                    solution[itr->second] = "Gold Medal";
                    break;
                case 2:
                    solution[itr->second] = "Silver Medal";
                    break;
                case 3:
                    solution[itr->second] = "Bronze Medal";
                    break;
                default:
                    solution[itr->second] = std::to_string(i);
                    break;
                }
            }
            
            return solution;
        }
    };
    

  • 0
    E

    In C++ maps are typically implemented as binary search trees.
    The worst case running time is O(n) for insertion of an element.
    So I think the running time should be O(n^2) in the worst case (we loop n times and insert into the map each time).


  • 0
    V

    @elyasin That is not true. Maps are implemented as redblack tree which guarantee lgN insertion and is an amortized constant. Refer http://www.cplusplus.com/reference/map/map/insert/ complexity section.


  • 0
    E

    You are right. I did not see that information, so I just made a general assumption. Thanks.


  • 0
    G

    @varun44 said in C++ simple map based NLogN:

    std::greater<int>

    What is the use of this clause here?


Log in to reply
 

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