# Middle-题目89：229. Majority Element II

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.

public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> list = new ArrayList<Integer>();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int num:nums) {
if(map.containsKey(num)) {
int count = map.get(num);
count++;
map.put(num,count);
if(count > nums.length/3 && !list.contains(num))
}
else {
map.put(num, 1);
if(nums.length < 3)
}
}
return list;
}
}

public class Solution {
public List<Integer> majorityElement(int[] nums) {
// 1, 2
List<Integer> res = new ArrayList<>();
if(nums==null || nums.length==0) return res;
if(nums.length==1) {
return res;
}

int m1 = nums[0];
int m2 = 0;

int c1 = 1;
int c2 = 0;

for(int i=1; i<nums.length; i++) {
int x = nums[i];
if(x==m1) ++c1;
else if(x==m2) ++c2;
else if(c1==0) {
m1 = x;
c1 = 1;
} else if(c2==0) {
m2 = x;
c2 = 1;
} else {
--c1; --c2;
}
}
c1 = 0; c2 = 0;
for(int i=0; i<nums.length; i++) {
if(m1 == nums[i]) ++c1;
else if(m2 == nums[i]) ++c2;
}
return res;
}
}

Cmershen的碎碎念：

• 本文已收录于以下专栏：

## 【leetcode】229. Majority Element II

【leetcode】229. Majority Element II

## 【LeetCode】229.Majority Element II解题报告

【LeetCode】229.Majority Element II解题报告tags: Array 题目地址：https://leetcode.com/problems/majority-element...

## [leetcode] 229. Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algori...

## 229. Majority Element II

class Solution { public: vector majorityElement(vector& nums) { unordered_map m; ...

## 153. Find Minimum in Rotated Sorted Array\229. Majority Element II\Moore's voting algorithm

Find Minimum in Rotated Sorted Array 题目描述 代码实现153. Find Minimum in Rotated Sorted Array题目描述一个已经排好序的数...

## leetcode 229:Majority Element II

举报原因： 您举报文章：Middle-题目89：229. Majority Element II 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)