Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
求大于数组一半的元素,思想主要是对于大于数组一般的元素,给起计数起计数总和一定可以大于其他元素总和,代码如下:
1 class Solution { 2 public: 3 int majorityElement(vector & nums) { 4 int count = 0; 5 int res; 6 int sz = nums.size(); 7 for(int i = 0; i < sz; ++i){ 8 if(count == 0){ 9 res = nums[i];10 count++;11 }else{12 if(res == nums[i])13 count++;14 else15 count--;16 }17 }18 return res; 19 }20 };