Shortest solution using just one std function


  • 0
    T

    The standard library contains the right function for this problem:

    int majorityElement(vector<int> &num) {
        nth_element(num.begin(), num.begin() + (num.size() / 2), num.end());
        return num[num.size() / 2];
    }
    

    O(N), no extra space (not even constant extra space) and just two lines of code.


  • 0
    I

    using nth_element -> no extra space at all
    oh, really?


  • 0
    P

    if nth_element implements selection rank algorithm then it indeed doesn't use extra space.


Log in to reply
 

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