您的位置:首页 > 编程语言 > Java开发

【leetcode】【169】Majority Element

2016-03-08 11:05 411 查看

一、问题描述

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.

二、问题分析

①排序,取中间值;②举个例子“1,1,1,2,3”,从头开始遍历,tmp指向第一个1,count=1;然后count=2,3;碰到2,count=2;碰到3,count=1;加入count=0,重新设置tmp值,并重新计数,最后输出tmp即可。具体的看代码。

三、Java AC代码

public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
public int majorityElement(int[] nums) {
int candidate = 0;
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (count == 0) {
candidate = nums[i];
count++;
} else if (nums[i] != candidate) {
count--;
} else {
count++;
}
}
return candidate;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode array