现在的位置: 首页 > 综合 > 正文

Majority Element

2016年06月06日 ⁄ 综合 ⁄ 共 977字 ⁄ 字号 评论关闭

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42247887

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)题意为给定一个整形数组,寻找出现次数大于数组长度一半的数字。

(2)这道题很简单。如果你对Arrays类比较熟悉的话,可以先运用其中的sort()方法对数组排序,排完序后再从左到右遍历遍历数组,并设置count记录遍历数字出现的次数,如果大于数组长度一半则返回。

(3)这道题如果不用上述方法,可以只遍历一次就得到结果,这里不再啰嗦了,详见下方代码。

(4)希望本文对你有所帮助。


算法代码实现如下:

public static int majorityElement(int[] num) {
	if(num==null ||num.length==0) return-1;
	if(num!=null &&num.length==1) return num[0];
	
	Arrays.sort(num);
	
	int count = 1;
	int flag = 0;
	for (int i = flag+1; i < num.length; i++) {
		if(num[flag]==num[i]){
			count++;
			if(count>num.length/2){
				return num[flag];
			}
		}else{
			flag=i;
			count=1;
		}
	}
	
	return -1;
}

只遍历一次算法的代码实现如下:

public static int majorityElement(int[] num) {
	if (num == null || num.length == 0)
		return -1;
	int count = 0;
	int index = 0;
	for (int i = 0; i < num.length; ++i) {
		if (index == 0)
			count = num[i];
		if (count == num[i])
			++index;
		else
			--index;
	}
	return count;
}

抱歉!评论已关闭.