代码面试题:Majority Number II

本文介绍了一种通过三三抵销的方法来找到数组中出现超过数组长度三分之一的元素,包括思路解析和具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.

Find it.

Note

There is only one majority number in the array

Example

For [1, 2, 1, 2, 1, 3, 3] return 1


思路:三三抵销,同时记录剩下的值各自出现的次数,出现次数多的值为答案。


public int majorityNumber2(int[] A){
    	if (A == null || A.length == 0) {
    		return -1;
    	}
    	
    	int candidate1 = 0;
    	int candidate2 = 0;
    	int count1 = 0;
    	int count2 = 0;
    	for (int i = 0; i < A.length; i++) {
    		if (count1 == 0) {
    			candidate1 = A[i];
    		}
    		if (count2 == 0 && A[i] != candidate1) {
    			candidate2 = A[i];
    		}
    		if (A[i] != candidate1 && A[i] != candidate2 
    				&& count1 != 0 && count2 != 0) {
    			count1--;
    			count2--;
    		} 
    		if (A[i] == candidate1) {
    			count1++;
    		}
    		if (A[i] == candidate2) {
    			count2++;
    		}
    	}
    	
    	if (count1 > count2) {
    		return candidate1;
    	} else {
    		return candidate2;
    	}
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值