C++ O(n) solution in three lines


  • 1
    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            vector<int>::iterator mid = nums.begin() + nums.size()/2;
            nth_element(nums.begin(), mid, nums.end());
            return (*mid);
        }
    };
    

    note that nth_element is in <algorithm> and runs in O(n) time.


Log in to reply
 

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