Majority 主元素1,2,3

本文介绍了三种不同的算法来解决寻找众数的问题。第一种算法适用于寻找出现次数超过一半的众数,第二种算法可以找出两个可能的候选众数,而第三种算法则能够找到出现频率最高的k个数中的一个。这些算法在遍历列表的过程中通过计数或投票的方式减少计算复杂度。

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

1. 1/2
public int majorityNumber(ArrayList<Integer> nums) {
		if (nums == null || nums.isEmpty()) return -1;
		// pair<key, count>
		int key = -1, count = 0;
		for (int num : nums) {
			// re-initialize
			if (count == 0) {
				key = num;
				count = 1;
				continue;
			}
			// increment/decrement count
			if (key == num) {
				count++;
			} else {
			count--;
			}
		} 
		return key;
		}

2. 1/3

public int majorityNumber(ArrayList<Integer> nums) {
		if (nums == null || nums.isEmpty()) return -1;
		// pair
		int key1 = -1, key2 = -1;
		int count1 = 0, count2 = 0;
		for (int num : nums) {
			if (count1 == 0) {
				key1 = num;
				count1 = 1;
				continue;
			} else if (count2 == 0 && key1 != num) {
				key2 = num;
				count2 = 1;
				continue;
			}
			if (key1 == num) {
				count1++;
			} else if (key2 == num) {
				count2++;
			} else {
				count1--;
				count2--;
			}
		} 
		count1 = 0;
		count2 = 0;
		for (int num : nums) {
			if (key1 == num) {
				count1++;
			} else if (key2 == num) {
				count2++;
			}
		}
		return count1 > count2 ? key1 : key2;
		}

3. 1/K

public int majorityNumber(ArrayList<Integer> nums, int k) {
		HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();
		if (nums == null || nums.isEmpty()) return -1;
		// update HashMap
		for (int num : nums) {
			if (!hash.containsKey(num)) {
				hash.put(num, 1);
				if (hash.size() >= k) {
					removeZeroCount(hash);
				}
			} else {
				hash.put(num, hash.get(num) + 1);
			}
		} // reset
		for (int key : hash.keySet()) {
			hash.put(key, 0);
		}
		for (int key : nums) {
			if (hash.containsKey(key)) {
				hash.put(key, hash.get(key) + 1);
			}
		} 
		// find max
		int maxKey = -1, maxCount = 0;
		for (int key : hash.keySet()) {
			if (hash.get(key) > maxCount) {
			maxKey = key;
			maxCount = hash.get(key);
			}
		} 
		return maxKey;
		} 
	private void removeZeroCount(HashMap<Integer, Integer> hash) {
		Set<Integer> keySet = hash.keySet();
		for (int key : keySet) {
		hash.put(key, hash.get(key) - 1);
		} 
		/* solution 1 */
		Iterator<Map.Entry<Integer, Integer>> it = hash.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<Integer, Integer> entry = it.next();
			if(entry.getValue() == 0) {
			it.remove();
		}
	    }
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值