Majority Element

来源:互联网 发布:假钞在淘宝中的暗语 编辑:程序博客网 时间:2024/06/05 16:11

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.

求出现次数超过一半的数。

定义result和t,如果nums[i]和result相同,t++,不同t--;t为0时重置result和t。

public int majorityElement(int[] nums) {int result=0,t=0;for(int i=0;i<nums.length;i++){if(t==0){result=nums[i];t=1;}else if(result==nums[i])t++;elset--;}return result;}


0 0
原创粉丝点击