Press "Enter" to skip to content

Posts tagged as “voting”

花花酱 LeetCode 229. Majority Element II

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]

Solution: Boyer–Moore Voting Algorithm

Time complexity: O(n)
Space complexity: O(1)

C++

Python3

Related Problem

花花酱 LeetCode 169. Majority Element

题目大意:给你一个数组,其中一个数出现超过n/2次,问你出现次数最多的那个数是什么?

Problem:

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Ideas:


Solution 1:

Hash table O(n) / O(n)

 

Solution 2:

BST O(nlogk) / O(n)

 

Solution 3:

Randomization O(n) / O(1)

 

Solution 4:

Bit voting O(n) / O(1)

 

Solution 5:

Moore Voting O(n) / O(1)

 

Solution 6:

Full sorting O(nlogn) / O(1)

 

Solution 7:

Partial sorting O(n) / O(1)

 

Solution 8:

Divide and conquer O(nlogn) / O(logn)

Divide and conquer O(nlogn) / O(logn)