LeetCode:Majority Element

Majority Element

Total Accepted: 74545  Total Submissions: 197687  Difficulty: Easy

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
  Divide and Conquer Array Bit Manipulation
Hide Similar Problems
  (M) Majority Element II


















思路:给每个数投票(票数>=0者胜出)。

先给nums[0]投,如果num[1]==nums[0],cnt++;

如果num[1]!=nums[0];cnt++;

如果cnt==0;投另外一个数。


code:

int majorityElement(int* nums, int numsSize) {
    
    int vote = nums[0]; 
    int cnt=1;
    for(int i=1;i<numsSize;i++) {
        if(vote==nums[i]) cnt++;
        else 
        {
            if(0==cnt){
                vote = nums[i];
                cnt++;
            }
            if(vote != nums[i]) cnt--;
        }
    }
    return vote;
}


你可能感兴趣的:(LeetCode,element,majority)