[Leetcode] Majority Element

来源:互联网 发布:最好的网络借贷平台 编辑:程序博客网 时间:2024/05/20 11:25

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.


public class Solution {    public int majorityElement(int[] nums) {    Arrays.sort(nums);    int i=0;    int count=1;    int len=nums.length;    if(len<3) return nums[0];    int compare=len>>1;    while(i<len-1)    {        if(nums[i]==nums[i+1])        {            count+=1;            i+=1;            if(count>compare) return nums[i];        }        else        {           count=1;              i+=1;        }                    }              return 0;      }}


0 0