LeetCode Majority Element II

Description:

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

Solution:

空间复杂度都要O(1),着实捉急了一下

后来百度到了一个算法,摩尔投票法,维基百科链接在这里   Boyer-Moore Majority Vote Algorithm

貌似很多LeetCode上面medium级别的题目,都要用到一些特殊的算法,包括前面遇到的manacher算法 Longest Palindromic Substring 编译原理中学到的逆波兰表达式 Basic Calculator

import java.util.*;

public class Solution {
	public List<Integer> majorityElement(int[] nums) {
		LinkedList<Integer> list = new LinkedList<Integer>();
		int n = nums.length;
		if (n == 0)
			return list;

		int candidateA = 0, candidateB = 0, countA = 0, countB = 0;
		for (int i = 0; i < n; i++) {
			if (nums[i] == nums[candidateA]) {
				countA++;
			} else if (nums[i] == nums[candidateB]) {
				countB++;
			} else if (countA == 0) {
				candidateA = i;
				countA = 1;
			} else if (countB == 0) {
				candidateB = i;
				countB = 1;
			} else {
				countA--;
				countB--;
			}
		}

		countA = 0;
		countB = 0;
		for (int i = 0; i < n; i++)
			if (nums[i] == nums[candidateA])
				countA++;
			else if (nums[i] == nums[candidateB])
				countB++;

		if (countA * 3 > n)
			list.add(nums[candidateA]);
		if (countB * 3 > n)
			list.add(nums[candidateB]);

		return list;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值