leetcode 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.



思路,

这个数字出现的次数,比其他所有元素的总和都要多。那就可以这样:

定义两个变量,一个记录当前major的出现次数,一个记录major。遍历时,若是两数相同,则次数加一。否则减1.若次数小于0,则替换当前的major.


int majorityElement(int* nums, int numsSize) {
    int major=nums[0];
    int flag=1;
    
    for(int i=1;i



你可能感兴趣的:(leetcode)