Majority Element
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.
- int majorityElement(vector<int> &num) {
- int nSize = num.size();
- int time = 0;
- int curValue = -1;
- for(int i=0;i<nSize;i++) {
- if(time == 0) {
- curValue = num[i];
- time = 1;
- } else {
- if(num[i] == curValue) {
- time++;
- } else {
- time--;
- }
- }
- }
- return curValue;
- }

浙公网安备 33010602011771号