C++.I think it's a good idea! But where is the problem? It works on [3,2,1,2,2,2], it doesn't work on [3,2,1,2,2,2,1].


  • 0
    O
    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            for(int i = 0; i < nums.size(); i++)
            {
                if(nums[i+1] && (nums[i] != nums[i+1]))
                {
                    nums.erase(nums.begin()+i);
                    nums.erase(nums.begin()+i);
                    i = -1;
                }
            }
            return nums[0];
        }
    };

  • 0
    M
    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            for(int i = 0; i < nums.size(); i++)
            {
                if(i + 1 < nums.size() && (nums[i] != nums[i+1]))
                {
                    nums.erase(nums.begin()+i);
                    nums.erase(nums.begin()+i);
                    i = -1;
                }
            }
            return nums[0];
        }
    };
    

    RuntimeError because you access an out-of-index element.
    The edited code can run, but TimeLimitExceed.


Log in to reply
 

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