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

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3]
Output: [3]

Example 2:

Input: [1,1,1,3,3,2,2,2]
Output: [1,2]

169. Majority Element 的拓展,这题要求的是出现次数大于n/3的元素,并且限定了时间和空间复杂度,因此不能排序,不能使用哈希表。

解法:Boyer-Moore多数投票算法 Boyer–Moore majority vote algorithm,T:O(n)  S: O(1) 摩尔投票法 Moore Voting

Java:

public List<Integer> majorityElement(int[] nums) {
if (nums == null || nums.length == 0)
return new ArrayList<Integer>();
List<Integer> result = new ArrayList<Integer>();
int number1 = nums[0], number2 = nums[0], count1 = 0, count2 = 0, len = nums.length;
for (int i = 0; i < len; i++) {
if (nums[i] == number1)
count1++;
else if (nums[i] == number2)
count2++;
else if (count1 == 0) {
number1 = nums[i];
count1 = 1;
} else if (count2 == 0) {
number2 = nums[i];
count2 = 1;
} else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for (int i = 0; i < len; i++) {
if (nums[i] == number1)
count1++;
else if (nums[i] == number2)
count2++;
}
if (count1 > len / 3)
result.add(number1);
if (count2 > len / 3)
result.add(number2);
return result;
}  

Python:

class Solution:
# @param {integer[]} nums
# @return {integer[]}
def majorityElement(self, nums):
if not nums:
return []
count1, count2, candidate1, candidate2 = 0, 0, 0, 1
for n in nums:
if n == candidate1:
count1 += 1
elif n == candidate2:
count2 += 1
elif count1 == 0:
candidate1, count1 = n, 1
elif count2 == 0:
candidate2, count2 = n, 1
else:
count1, count2 = count1 - 1, count2 - 1
return [n for n in (candidate1, candidate2)
if nums.count(n) > len(nums) // 3]

Python:

class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
k, n, cnts = 3, len(nums), collections.defaultdict(int) for i in nums:
cnts[i] += 1
# Detecting k items in cnts, at least one of them must have exactly
# one in it. We will discard those k items by one for each.
# This action keeps the same mojority numbers in the remaining numbers.
# Because if x / n > 1 / k is true, then (x - 1) / (n - k) > 1 / k is also true.
if len(cnts) == k:
for j in cnts.keys():
cnts[j] -= 1
if cnts[j] == 0:
del cnts[j] # Resets cnts for the following counting.
for i in cnts.keys():
cnts[i] = 0 # Counts the occurrence of each candidate integer.
for i in nums:
if i in cnts:
cnts[i] += 1 # Selects the integer which occurs > [n / k] times.
result = []
for i in cnts.keys():
if cnts[i] > n / k:
result.append(i) return result def majorityElement2(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return [i[0] for i in collections.Counter(nums).items() if i[1] > len(nums) / 3]  

C++:

class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> res;
int m = 0, n = 0, cm = 0, cn = 0;
for (auto &a : nums) {
if (a == m) ++cm;
else if (a ==n) ++cn;
else if (cm == 0) m = a, cm = 1;
else if (cn == 0) n = a, cn = 1;
else --cm, --cn;
}
cm = cn = 0;
for (auto &a : nums) {
if (a == m) ++cm;
else if (a == n) ++cn;
}
if (cm > nums.size() / 3) res.push_back(m);
if (cn > nums.size() / 3) res.push_back(n);
return res;
}
};

C++:

vector<int> majorityElement(vector<int>& nums) {
int cnt1 = 0, cnt2 = 0, a=0, b=1; for(auto n: nums){
if (a==n){
cnt1++;
}
else if (b==n){
cnt2++;
}
else if (cnt1==0){
a = n;
cnt1 = 1;
}
else if (cnt2 == 0){
b = n;
cnt2 = 1;
}
else{
cnt1--;
cnt2--;
}
} cnt1 = cnt2 = 0;
for(auto n: nums){
if (n==a) cnt1++;
else if (n==b) cnt2++;
} vector<int> res;
if (cnt1 > nums.size()/3) res.push_back(a);
if (cnt2 > nums.size()/3) res.push_back(b);
return res;
}

  

  

类似题目:

[LeetCode] 169. Majority Element 多数元素

  

All LeetCode Questions List 题目汇总

[LeetCode] 229. Majority Element II 多数元素 II的更多相关文章

  1. leetcode 229 Majority Element II

    这题用到的基本算法是Boyer–Moore majority vote algorithm wiki里有示例代码 1 import java.util.*; 2 public class Majori ...

  2. LeetCode 229. Majority Element II (众数之二)

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

  3. leetcode 229. Majority Element II(多数投票算法)

    就是简单的应用多数投票算法(Boyer–Moore majority vote algorithm),参见这道题的题解. class Solution { public: vector<int& ...

  4. Java for LeetCode 229 Majority Element II

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

  5. (medium)LeetCode 229.Majority Element II

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

  6. [LeetCode] 169. Majority Element 多数元素

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  7. leetcode 169. Majority Element 、229. Majority Element II

    169. Majority Element 求超过数组个数一半的数 可以使用hash解决,时间复杂度为O(n),但空间复杂度也为O(n) class Solution { public: int ma ...

  8. 【刷题-LeetCode】229. Majority Element II

    Majority Element II Given an integer array of size n, find all elements that appear more than ⌊ n/3 ...

  9. 【LeetCode】229. Majority Element II

    Majority Element II Given an integer array of size n, find all elements that appear more than ⌊ n/3 ...

随机推荐

  1. D. Nested Segments(树状数组、离散化)

    题目链接 参考博客 题意: 给n个线段,对于每个线段问它覆盖了多少个线段. 思路: 由于线段端点是在2e9范围内,所以要先离散化到2e5内(左右端点都离散化了,而且实际上离散化的范围是4e5),然后对 ...

  2. 米勒罗宾素数检测(Miller-Rabin)

    适用范围:较大数的较快素性判断 思路: 因为有好的文章讲解具体原理(见参考文章),这里只是把代码的大致思路点一下,读完了文章如果还有些迷糊,可以参考以下解释 原理是费马小定理:如果p是素数,则a^(p ...

  3. 当电脑上有两个mysql时,如何让jmeter连接自己需要的那个mysql

    1.当有两个mysql时,修改其中一个的mysql端口号为3307 ,也可以是其他8788, 在文件my.ini中修改端口号为:3307:修改完之后记得重启mysql哦:dos下命令可以用net st ...

  4. python图像处理库Pillow基本使用方法

    安装pillow pillow的文档页面,documentation of Pillow 生成一个有单一颜色的图像 from PIL import Image, ImageDraw img = Ima ...

  5. 【http】认识HTTP

    HTTP基础概念 我们学计算机网络的时候就知道,我们把计算机网络分层了5层,一般我们现在用的都是TCP/IP这么一个分层结构. 虽然官方的是ISO 提出的7层结构,但是仅仅是理论基础,在实际上大多人都 ...

  6. 原生js打地鼠

    我们要做的是一个打地鼠的游戏,只用原生js 1.导入需要的图片 2.编写页面css样式demo.css *{ margin:0; padding:0; } .game{ position: relat ...

  7. 利用Xilinx ROM仿真时注意包括.mif文件

    利用Xilinx ROM仿真时,注意包括.mif文件.一般是将.v文件和.mif文件放在同一个目录下,以便.v文件读取.mif数据.如不注意,就不会读出有效数据.

  8. 03-树2 List Leaves (25 分)

    Given a tree, you are supposed to list all the leaves in the order of top down, and left to right. I ...

  9. Spark跑在Yarn上出现错误,原因是jdk的版本问题

    ./bin/spark-shell --master yarn 2019-07-01 12:20:13 WARN NativeCodeLoader:62 - Unable to load native ...

  10. 错误: 找不到或无法加载主类 Welcome.java

    问题原因: 不需要带.java