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];
}
};
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].

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 outofindex element.
The edited code can run, but TimeLimitExceed.