Leetcode_169_Majority Element

97 篇文章 0 订阅
94 篇文章 18 订阅

本文是在学习中的总结,欢迎转载但请注明出处: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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值