leetcode Majority Element

来源:互联网 发布:java string split n 编辑:程序博客网 时间:2024/06/05 12:48

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<numsSize;i++)    {        if(nums[i]!=major)            flag--;        else            flag++;        if(flag<0){            major = nums[i];            flag=0;        }    }        return major;}



0 0
原创粉丝点击