您的位置:首页 > 其它

[LeetCode][数论]Majority Element

2016-03-21 15:30 141 查看
题目描述:

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.

思路:

前提条件:数据中有一个元素出现的个数超过数组长度的一半,求出这个元素

过程:要找出数组中出现个数最多的元素,遍历和计数是一定的,最基本的是HashMap存储,但能不能节省一点存储空间呢?因为题目给定的是出现的个数超过其他所有的数字,所以可以采用一个标记元素,记录一个数据,策略是:如果元素i是记录下来的数据,计数加一;如果当前计数为0,说明之前不存在出现超过数据长度二分之一的数字,重复将当前元素赋值给标记元素,计数为1;如果元素i既不是当前记录元素,计数值也不为0,则应该将计数减一,抵消依次出现的次数,最后,返回当前记录元素

代码实现:

public class Solution {
public int majorityElement(int[] nums) {
if(nums.length == 1){
return nums[0];
}

int m1 = nums[0];
int c1 = 0;

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