题解|超过数组长度一半的数字

超过数组长度一半的数字

描述
数组中有一个数字的出现次数超过了该数组长度的一半,找出这个数字。

思路

  1. 排序后返回arr[arr.length/2]。
  2. 排序后扫描。
  3. 超过数组长度一半的数字,其次数累加和一定大于其余数字的累加和。所以可以直接遍历数组,保存当前数字和出现次数,相同数字count++否则count- -,若count = 0则重置当前数字和出现次数。遍历完成后,返回保存的数字。

下面给出的是思路3的代码,时间复杂度为O(n)

public class 哪个数字超过了一半_03 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr = { 1, 0, 1, 2, 1 };
		System.out.println(f(arr));
	}

	// 超过数组长度一半的数字次数累加和一定大于其余数字的累加和
	// 此时算法复杂度为O(n)
	private static int f(int[] arr) {
		int len = arr.length;
		int result = arr[0];
		int count = 1;

		for (int i = 1; i < len; i++) {
			if (arr[i] == result) {
				count++;
			} else {
				count--;
			}
			if (count == 0) {
				result = arr[i];
				count = 1;
			}
		}
		return result;
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值