# LeetCode 229 Majority Element II（主要元素II）（Array）（Boyer–Moore majority vote algorithm）

938人阅读 评论(0)

## 原文

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.

Hint:

How many majority elements could it possibly have?

## 分析

The Boyer-Moore Vote Algorithm solves the majority vote problem in linear time O(n)$O(n)$and logarithmic space O(logn)$O(\log n)$. The majority vote problem is to determine in any given sequence of choices whether there is a choice with more occurrences than half of the total number of choices in the sequence and if so, to determine this choice. Note how this definition contrasts with the mode in which it is not simply the choice with the most occurrences, but the number of occurrences relative to the total length of the sequence.

Mathematically, given a finite sequence (length n) of numbers, the object is to find the majority number defined as the number that appears more than n/2$⌊ n/2 ⌋$ times.

import java.util.*;
public class MajorityVote {
public int majorityElement(int[] num) {
int n = num.length;
int candidate = num[0], counter = 0;
for (int i : num) {
if (counter == 0) {
candidate = i;
counter = 1;
} else if (candidate == i) {
counter++;
} else {
counter--;
}
}

counter = 0;
for (int i : num) {
if (i == candidate) counter++;
}
if (counter <= n / 2) return -1;
return candidate;
}
public static void main(String[] args) {
MajorityVote s = new MajorityVote();
System.out.format("%d\n", s.majorityElement(new int[] {1, 2, 3}));
System.out.format("%d\n", s.majorityElement(new int[] {2, 2, 3}));
}
}

## 代码

Java

public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> marjority = new ArrayList<>();
int n = nums.length;
int candidate1 = 0, candidate2 = 0, counter1 = 0, counter2 = 0;
for (int i : nums) {
if (candidate1 == i) {
counter1++;
} else if (candidate2 == i) {
counter2++;
} else if (counter1 == 0) {
candidate1 = i;
counter1 = 1;
} else if (counter2 == 0) {
candidate2 = i;
counter2 = 1;
} else {
counter1--;
counter2--;
}
}
counter1 = 0;
counter2 = 0;
for (int i : nums) {
if (i == candidate1) counter1++;
else if (i == candidate2) counter2++;
}
return marjority;
}
}
4
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：1368881次
• 积分：22089
• 等级：
• 排名：第321名
• 原创：521篇
• 转载：0篇
• 译文：29篇
• 评论：805条
Billboard：
微博
博客专栏
 UWP通用应用开发 文章：6篇 阅读：17121
 Android 开发 文章：6篇 阅读：16505
 LeetCode 文章：27篇 阅读：69451
 算法 文章：9篇 阅读：67148
 Windows App开发 文章：37篇 阅读：130147
 欧拉工程 文章：0篇 阅读：0
 OpenCV归纳 文章：5篇 阅读：19729
 Scheme归纳 文章：13篇 阅读：63448
 SICP练习 文章：151篇 阅读：258678
最新评论