Majority Number

原题链接:http://lintcode.com/en/problem/majority-number/#

Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

Example

For [1, 1, 1, 1, 2, 2, 2], return 1

Challenge

O(n) time and O(1) space

SOLUTION 1:

http://www.geeksforgeeks.org/majority-element/

这里是一篇论文: http://www.cs.utexas.edu/~moore/best-ideas/mjrty/

这里用的算法是:MJRTY - A Fast Majority Vote Algorithm

1. 简单来讲,就是不断对某个议案投票,如果有人有别的议案,则将前面认为的议案的cnt减1,减到0换一个议案。

如果存在majority number,那么这个议案一定不会被减到0,最后会胜出。

2. 投票完成后,要对majority number进行检查,以排除不存在majority number的情况。如 1,2,3,4这样的数列,是没有majory number的。

很简单,统计一下结果议案的票数,没有过半就是没有majority number.

摘录一段解释:

METHOD 3 (Using Moore’s Voting Algorithm)

This is a two step process.
1. Get an element occurring most of the time in the array. This phase
will make sure that if there is a majority element then it will return
that only.
2. Check if the element obtained from above step is majority element.

1. Finding a Candidate:
The algorithm for first phase that works in O(n) is known as Moore’s
Voting Algorithm. Basic idea of the algorithm is if we cancel out each
occurrence of an element e with all the other elements that are
different from e then e will exist till end if it is a majority element.

findCandidate(a[], size)
1. Initialize index and count of majority element
maj_index = 0, count = 1
2. Loop for i = 1 to size – 1
(a)If a[maj_index] == a[i]
count++
(b)Else
count--;
(c)If count == 0
maj_index = i;
count = 1
3. Return a[maj_index]

Above algorithm loops through each element and maintains a count of a[maj_index], If next element is same then increments the count, if next element is not same then decrements the count, and if the count reaches 0 then changes the maj_index to the current element and sets count to 1.
First Phase algorithm gives us a candidate element. In second phase we
need to check if the candidate is really a majority element. Second
phase is simple and can be easily done in O(n). We just need to check if
count of the candidate element is greater than n/2.

Example:
A[] = 2, 2, 3, 5, 2, 2, 6
Initialize:
maj_index = 0, count = 1 –> candidate ‘2?
2, 2, 3, 5, 2, 2, 6

Same as a[maj_index] => count = 2
2, 2, 3, 5, 2, 2, 6

Different from a[maj_index] => count = 1
2, 2, 3, 5, 2, 2, 6

Different from a[maj_index] => count = 0
Since count = 0, change candidate for majority element to 5 => maj_index = 3, count = 1
2, 2, 3, 5, 2, 2, 6

Different from a[maj_index] => count = 0
Since count = 0, change candidate for majority element to 2 => maj_index = 4
2, 2, 3, 5, 2, 2, 6

Same as a[maj_index] => count = 2
2, 2, 3, 5, 2, 2, 6

Different from a[maj_index] => count = 1

Finally candidate for majority element is 2.

First step uses Moore’s Voting Algorithm to get a candidate for majority element.

2. Check if the element obtained in step 1 is majority

printMajority (a[], size)
1. Find the candidate for majority
2. If candidate is majority. i.e., appears more than n/2 times.
Print the candidate
3. Else
Print "NONE"
 package Algorithms.lintcode.math;

 import java.util.ArrayList;

 public class MajorityNumber {
/**
* @param nums: a list of integers
* @return: find a majority number
*/
public int majorityNumber(ArrayList<Integer> nums) {
// write your code
if (nums == null || nums.size() == 0) {
// No majority number.
return -1;
} int candidate = nums.get(0); // The phase 1: Voting.
int cnt = 1;
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i) == candidate) {
cnt++;
} else {
cnt--;
if (cnt == 0) {
candidate = nums.get(i);
cnt = 1;
}
}
} // The phase 2: Examing.
cnt = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums.get(i) == candidate) {
cnt++;
}
} // No majory number.
if (cnt <= nums.size() / 2) {
return -1;
} return candidate;
}
}

2014.12.27 REDO:

 public int majorityElement(int[] num) {
if (num == null || num.length == 0) {
return -1;
} int maj = num[0]; int len = num.length;
int cnt = 1;
for (int i = 1; i < len; i++) {
if (cnt == 0) {
maj = num[i];
cnt = 1;
} else if (num[i] != maj) {
cnt--;
} else {
cnt++;
}
} return maj;
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/math/MajorityNumber.java

Lintcode: Majority Number 解题报告的更多相关文章

  1. Lintcode: Majority Number III

    Given an array of integers and a number k, the majority number is the number that occurs more than 1 ...

  2. 【九度OJ】题目1040:Prime Number 解题报告

    [九度OJ]题目1040:Prime Number 解题报告 标签(空格分隔): 九度OJ 原题地址:http://ac.jobdu.com/problem.php?pid=1040 题目描述: Ou ...

  3. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  4. 【LeetCode】306. Additive Number 解题报告(Python)

    [LeetCode]306. Additive Number 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http: ...

  5. Lintcode: Majority Number II 解题报告

    Majority Number II 原题链接: http://lintcode.com/en/problem/majority-number-ii/# Given an array of integ ...

  6. [LintCode] Majority Number 求众数

    Given an array of integers, the majority number is the number that occurs more than half of the size ...

  7. Lintcode: Majority Number II

    Given an array of integers, the majority number is the number that occurs more than 1/3 of the size ...

  8. LintCode Majority Number II / III

    Given an array of integers, the majority number is the number that occurs more than 1/3 of the size ...

  9. [LintCode] Majority Number 求大多数

    Given an array of integers, the majority number is the number that occurs more than half of the size ...

随机推荐

  1. Python实现鸢尾花数据集分类问题——基于skearn的SVM

    Python实现鸢尾花数据集分类问题——基于skearn的SVM 代码如下: # !/usr/bin/env python # encoding: utf-8 __author__ = 'Xiaoli ...

  2. Oslo 相机 App

    https://itunes.apple.com/cn/app/osho/id1203312279?mt=8.它支持1:1,4:3,16:9多种分辨率拍摄,滤镜可在取景框的实时预览,拍摄过程可与滤镜实 ...

  3. zabbix邮件告警之 通过shell脚本发送告警

    说明:本文讲如何通过shell脚本实现zabbix发送告警邮件,共有5步1.设置mailx账号:是配置mailx的发信账号2.zabbix服务器端编写邮件发送脚本:是增加zabbix的告警方式,增加通 ...

  4. IT编年史 技术生命周期起步,成长,成熟和衰退四个阶段 IT历史总结

    IT编年史 最近查看了大量的正史或者野史,体会了整个IT夜发展的风气云涌,颇为激动,撰写如下. 感谢google黑板报的浪潮之巅http://googlechinablog.com/2007/07/a ...

  5. C语言学习笔记 (004) - 数组名和数组首地址(转)

    一个变量有地址,一个数组包含若干元素,每个数组元素都在内存中占用存储单元,它们都有相应的地址.指针变量既然可以指向变量,当然也可以指向数组和数组元素(把数据起始地址或某一元素的地址放到一个指针变量中) ...

  6. Linux安装最新版Mono,Jexus(截至2015年12月30日)

    安装系统必备: yum -y install gcc gcc-c++ bison pkgconfig glib2-devel gettext make libpng-devel libjpeg-dev ...

  7. 第2章 Python基础-字符编码&数据类型 列表&元祖 练习题

    1.创建一个空列表,命名为names,往里面添加old_driver,rain,jack,shanshan,peiqi,black_girl元素 names = ["old_driver&q ...

  8. U811.1接口EAI系列之二-BOM构成-委外BOM构成--VB语言

    1.下面代码实现了VB6.0中调用U8EAI-BOM构成服务,以下代码均为项目实际代码,可直接复制应用. 2.在u811.1版本中委外BOM构成与正常的BOM构成是同系列表,不单独存储. 3.是以存货 ...

  9. laravel5.7的redis配置,一直报错Class 'Predis\Client' not found

    laravel5.7的redis配置,一直报错Class 'Predis\Client' not found 首先我检查了配置,和composer 都没有错,用原生的redis也可以正常连接和读写. ...

  10. unity, Gizmos.DrawMesh一个坑

    错误写法(画不出来): void OnDrawGizmos(){ Mesh mesh=new Mesh(); mesh.vertices=... mesh.triangles=... //mesh.R ...