Help! Time limit exceeded/ C++

  • 0

    class Solution {
    int majorityElement(vector<int>& nums) {

        for(int i=0;i<nums.size();i++)
        {   //int index=nums[i];
            int counter=0;
            for(int j=i;j<nums.size();j++)
            {    if (nums[j]==nums[i])
            if (counter>floor(nums.size()/2))
                return nums[i]; 


  • 1

    Your solution is O(n^2) time.

    The majority element is the element that appears more than ⌊ n/2 ⌋ times.
    So it must be the middle one of the sorted array.

    My javascript code:

    var majorityElement = function(nums) {
        return nums.sort()[Math.floor(nums.length / 2)];

    It takes O(nlgn).

  • 0

    Wow, your code is really short and simple. Thanks for helping me out!

Log in to reply

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