letecode [169] - 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.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

Subject to the effect :

   Find the mode array.

Understanding:

   God, look at the big solution.

  Val mark the largest number of elements, encountering the same number count ++, encounter different number count--, when the count is equal to 0, update val is a new element.

Code C ++:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int val = nums[0];
        int count=1;
        int i;
        for(i=1;i<nums.size();++i){
            if(count==0)
                val = nums[i];
            if(nums[i]==val)
                count++;
            else
                count--;
        }
        return val;
    }
};

operation result:

   When execution: 28 ms, beat the 81.41% of all users to submit in C ++

   Memory consumption: 11 MB, defeated 87.66% of all users to submit in C ++

Guess you like

Origin www.cnblogs.com/lpomeloz/p/11004189.html