Majority Element in an Array
Problem Statement
Given a large array of non-negative integer numbers, write a function which determines whether or not there is a number that appears in the array more times than all other numbers combined. If such element exists, function should return its value; otherwise, it should return a negative value to indicate that there is no majority element in the array.
Example: Suppose that array consists of values 2, 6, 1, 2, 2, 4, 7, 2, 2, 2, 1, 2. Majority element in this array is number 2, which appears seven times while all other values combined occupy five places in the array.
Keywords: Array, searching, majority, vote.
Problem Analysis
This problem can be viewed as the task of counting votes, where number of candidates is not determined in advance. Goal is to see if any of the candidates has collected more than half of all votes.
We could approach the problem in several ways. For example, we could sort the array and then simply count how many times each candidate appears. Since all occurrences of one value in sorted sequence are consecutive, determining the winner would be very simple. Here is the pseudo-code:
function FindMajoritySort(a, n)
a - unsorted integer array
n - number of elements in the array
begin SortArray(a, n) -- use external function for sorting winner = -
winCount = curCount = for i = , n -
begin
if a[i] = cur then
curCount = curCount +
else if curCount > winCount then
winner = a[i - ]
winCount = curCount
curCount =
else
curCount =
end if curCount > winCount
begin
winner = a[n - ]
winCount = curCount
end if winCount <= n - winCount then
winner = - return winner end
This function is very efficient once the array is sorted. However, sorting the array takes time - O(NlogN) in general - and that will be the overall time complexity of this solution.
We might tackle the time complexity problem by somehow indexing the values while traversing the array. As long as data structure used to keep the counters runs in less than O(logN) time per read or write operation, we will be fine. And really, there is such a structure: hash table takes O(1) time to store a value or to find it. Here is the pseudo-code of the solution which relies on hash table to count how many times each element occurs in the array:
function FindMajorityHash(a, n)
a - unsorted integer array
n - number of elements in the array
begin hashtable -- used to index counts for each value winner = - for i = , n -
begin count =
if hashtable.Contains(a[i]) then
count = hashtable(a[i]) + hashtable(a[i]) = count if winner < or count > hashtable(winner) then
winner = a[i] end if * hashtable(winner) <= n then
winner = - return winner end
This function runs in O(N) time, but suffers a problem of a different sort. It requires additional space for the hash table, which is proportional to N. For a very large array, this may be a serious obstacle.
By this point we have devised one solution which runs in O(NlogN) time and O(1) space; another solution runs in O(N) time and O(N)space. Neither of the two is really good. It would be beneficial if we could devise a solution that takes good parts of both, i.e. a solution that runs in constant space and completes in time that is proportional to length of the array. We will try to construct a solution that runs in O(N) time and O(1) space.
We could run through the array and let that number outperform all other numbers. For instance, whenever we encounter value M in the array, we would increment some counter. On any other value, we would decrement the counter. Current value stored in the counter is the information which survives during the array traversal. It would go up and down, or might even be negative sometimes. But when end of the array is reached, value in the counter will definitely be positive because there was more increment than decrement operations. Figure below shows an example in which we are proving that number 1 is the majority value in an array.

When this modified solution is applied to the whole array, we end up with a number which is the last majority candidate. We are still not sure whether this number is overall majority element of the array or not. But the selection process adds some qualities to that candidate. Let's observe the previous array when processed by this new algorithm.

This time counter never goes into negative. It always bounces off the zero value and turns back into positive range, at the same time switching to the new majority candidate. The whole process now divides the array into segments. In each segment one number occurs as many times as all other numbers combined. In the worst case, those "all other numbers" will actually be a single number which occurs as many times as the candidate for that segment - we don't know whether that is the case or not, because we are counting only the candidate’s occurrences.
Anyway, when all segments align, the last segment alone decides the battle, and here is why. All segments except the last one look the same. First number in the segment is the special element and it occurs as many times as all other numbers in the segment combined. We know this fact because every segment ends with counter equal to zero (this is what candidate selection process guarantees). So all segments but the last one together are guaranteed not to contain a majority element. At best, there will be one number that occurs as many times as all the others combined, but not more than that. The only number that really could be the majority element of the array is the winner of the last segment, i.e. final majority candidate that remains when end of array is reached.
This complete solution requires a couple of variables to store current candidate and the counter. It passes the array once or twice. In the first pass, majority candidate is established. In the second pass we simply check whether the candidate is a solution or there is no majority element. This means that algorithm described runs in O(N) time and O(1) space.
Implementation will consist of two functions. First one will count occurrences of a number, subtracting other elements from the count. Majority element will be the value for which this function returns positive result. Another function will establish the majority candidate and then call the first function to decide whether it is the majority element or there is no majority element in the array. Here is the pseudo-code:
function GetCountForValue(a, n, x)
a - array of non-negative integers
n - number of elements in the array
x - number for which count is required
begin count = for i = , n-
begin
if a[i] = x then
count = count +
else
count = count -
end return count end function FindMajorityElement(a, n)
a - array of non-negative integers
n - number of elements in the array
begin count =
candidate = a[] for i = , n-
begin if a[i] = candidate then
count = count +
else if count = then
candidate = a[i]
count =
else
count = count – end if count > then
count = GetCountForValue(a, n, candidate) if count > then
return candidate return - -- there is no majority element end
Implementation
Below are functions GetCountForValue and FindMajorityElement, coded in C#. The code is relatively simple, once all the analysis has been provided.
static int GetCountForValue(int[] a, int x)
{ int count = ; for (int i = ; i < a.Length; i++)
if (a[i] == x)
count++;
else
count--; return count; } static int FindMajorityElement(int[] a)
{ int count = ;
int candidate = a[]; for (int i = ; i < a.Length; i++)
{
if (a[i] == candidate)
{
count++;
}
else if (count == )
{
candidate = a[i];
count = ;
}
else
{
count--;
}
} if (count > )
count = GetCountForValue(a, candidate); if (count > )
return candidate; return -; }
Quote From:
Exercise #9: Finding a Majority Element in an Array
Majority Element in an Array的更多相关文章
- 169. Majority Element(C++)
169. Majority Element Given an array of size n, find the majority element. The majority element is t ...
- Majority Element,Majority Element II
一:Majority Element Given an array of size n, find the majority element. The majority element is the ...
- 23. leetcode 169. Majority Element
169. Majority Element Given an array of size n, find the majority element. The majority element is t ...
- 【LEETCODE】35、169题, Majority Element
package y2019.Algorithm.array; import java.util.HashMap; import java.util.Map; /** * @ProjectName: c ...
- Week1 - 169.Majority Element
这周刚开始讲了一点Divide-and-Conquer的算法,于是这周的作业就选择在LeetCode上找分治法相关的题目来做. 169.Majority Element Given an array ...
- Algo: Majority Element
Approach #1 Brute Force Intuition We can exhaust the search space in quadratic time by checking w ...
- LeetCode169 Majority Element, LintCode47 Majority Number II, LeetCode229 Majority Element II, LintCode48 Majority Number III
LeetCode169. Majority Element Given an array of size n, find the majority element. The majority elem ...
- (Array)169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appear ...
- 169. Majority Element (Array)
Given an array of size n, find the majority element. The majority element is the element that appear ...
随机推荐
- C# 编写简易 ASP.NET Web 服务器
C# 编写简易 ASP.NET Web 服务器 你是否有过这样的需求——想运行 ASP.NET 程序,又不想安装 IIS 或者 Visual Studio?我想如果你经常编写 ASP.NET 程序的话 ...
- 纯Python综合图像处理小工具(2)图像增强
<背景> 这次分享的脚本是对图像进行增强处理,包含对图像像素的色彩增强.亮度增强.对比度增强.图像尖锐化等增强操作,主要基于PIL包的lambda和ImageEnhance模块. 使用方法 ...
- Android 检测是否连接蓝牙耳机
前言 欢迎大家我分享和推荐好用的代码段~~ 声明 欢迎转载,但请保留文章原始出处: CSDN:http://www.csdn.net ...
- Swift3.0服务端开发(四) MySQL数据库的连接与操作
本篇博客我们来聊聊MySQL数据库的连接与操作.如果你本地没有MySQL数据库的话,需要你先安装MySQL数据库.在Mac OS中使用brew包管理器进行MySQL的安装是及其方便的.安装MySQL的 ...
- 关于preg_match()函数的一点小说明
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $ ...
- make -j 多核并行编译 导致笔记本过热 自动关机保护
中午在装着CentOS的笔记本上把 Oneinstack 跑起来然后去上班了,本来等着下班回来用的,回来之后发现是关机状态,环境也没有装好. 查看日志,找不到相关信息,甚至还以为是被入侵了.又试了几遍 ...
- iOS解析crash日志:
iOS解析crash日志:我们在ios开发中会碰到的很多crash问题,如果Debug调试模式的话,我们可以往往很容易的根据log的输出定位到导致crash的原因,但对于已经上线的应用,或者是rele ...
- [SOJ]寻找第k大数字(numberk)
Description 经过长时间的筹备工作,在Jourk,Ronny,Plipala,阿长,阿沈等人的努力下,DM实验室建立起自己的系列网站,其中包括三个大板块:DMOJ首页.DMOJ论坛.DMOJ ...
- class.forname()方法的学习(转)
Class.forName(xxx.xx.xx) 返回的是一个类 首先你要明白在java里面任何class都要装载在虚拟机上才能运行.这句话就是装载类用的(和new 不一样,要分清楚). 至于什么时候 ...
- 为jEasyUi的日期控件添加一个“清空”按钮----通过修改1.4的easyui.min.js
为 jQuery EasyUI 1.4 的datebox或datetimebox添加一个清空按钮 使用场景:为用户指定了日期的格式,且日期可以为空 修改语言包easyui-lang-zh_CN.js ...