Majority Element:找最多且多于一半的元素

来源:互联网 发布:数据库证书哪个好考 编辑:程序博客网 时间:2024/05/29 18:46

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.


思路:之前写了一遍,然后因为敏感词被封了.....不敢多写了,方法是摩/尔/投/票/法,自己百度吧,我都不知道哪个词敏感....

class Solution {    public int majorityElement(int[] nums) {        int count = 1;        int majority = nums[0];        for(int i = 1;i<nums.length;i++){            if(nums[i]!=majority){                count--;                if(count<=0){                    majority = nums[i];                    count = 1;                }            }else{                count++;            }        }        return majority;    }}


阅读全文
0 0