寻找多数元素这一问题主要运用了:Majority Vote Alogrithm(最大投票算法)
1.Majority Element

1)description

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.

注意3点:这里的多数元素必须严格大于⌊ n/2 ⌋(向下取整)、题目假定数组非空、假定最大元素一定存在(并且我们可以知道满足要求的元素仅1个)。

eg:[1,2,7,2,2,5,10,2,2]   n=9  最多数元素为2,因为它出现次数为5>⌊ 9/2 ⌋=4.

     2)solutions

链接中有leetcoder的六种方案,例如最直观的哈希表:map遍历时通过对相同数组元素逐一累加可以筛选出满足条件的元素,这一方案对Majority Element II也适用;或者通过对数组先排序,那么取出数组索引为⌊ n/2 ⌋的元素即可;又有随机抽取数组中的元素然后求其出现次数,由于最多数元素为⌊ n/2 ⌋个,所以最糟情况下猜了⌊ n/2 ⌋次;分治法;最大投票算法。

3)最大投票算法原理:

遍历数组,当碰到两个不一样的数字时,将这两个数字同时丢弃,这两个数字中可能有一个为 Majority Element,也可能两个都不为Majority Element.因为k 大于 n/2,所以在最差情况下(每次移除不同数字时都包含一个Majority Element),我们仍然能够保证最后得到的数字是Majority Element.总之:在原序列中去除两个不同的元素后,在原序列中的多数元素在新序列中还是多数元素

根据《算法设计技巧与分析》书中的算法可以写出如下非递归代码(书中为递归版本并且附有检查候选的最多数元素是否存在):

class Solution {
public:
int majorityElement(vector<int>& nums) {
int j,candidate,count; //candidate代表候选解即最多数元素,count代表票数
for (j = ; j < nums.size(); j++){
candidate = nums[j]; count = ; //起初假定第一个元素即为candidate且票数为1,当票数count=0时就换candidate
while (j < nums.size() - && count>){
j = j + ;
if (nums[j] == candidate) count++; //当下一个元素与candidate相等时票数+1
else count--; //否则票数-1
}
}
return c;
}
};

下面代码和上面完全一样,只是更直观一点:

class Solution {
public:
int majorityElement(vector<int>& nums) {
int candidate, count = , n = nums.size();
for (int i = ; i < n; i++) {
if (count==) { //票数为0则换candidate,换了candidate票数就得变为1
candidate = nums[i];
count = ;
}
else if(nums[i] == candidate) //下一个元素和candidate相等时票数+1
count++;
else
count--; //不相等票数-1
}
return candidate;
}
};

总结:因为数组个数为n,且最多数元素个数>⌊ n/2 ⌋,所以有且只有1个元素满足条件,所以设置了一个candidate和一个计票器count。而 Majority Element II要求是最多数元素个数>⌊ n/3 ⌋,所以至多有2个元素满足要求,所以需要设置两个candidate和两个计票器count

2.Majority Element II

1)description: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.

2)思路:我们需要找到三个不同的数字,然后抛弃掉这三个数字:首先要判断是否等于candidate,如果等于candidate那么对应的 candidate 必须加一等待其他的数字来消除它,当有一个 candidate 的 count 为 0 时,说明该 candidate 已经全部被消除,我们需要设定新的 candidate 数字。当一个数字不等于两个 candidate,同时两个 candidate 的 count 都不为零。这意味着当前这个数字就是这两个candidate 等待的第三个数字。于是这三个数字被移除,同时它们的的 count 都要减一。

eg:[2,1,1,4,6,1,10]       n=7   元素1的个数为3>⌊ 7/3 ⌋=2

[2,1,1,1,10,2,2,1]    n=8   元素1个数为4>⌊ 8/3 ⌋=2,元素2的个数为3>⌊ 8/3 ⌋=2

python代码:

class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return []
count1, count2, candidate1, candidate2 = , , , 0 //初始化两个candidate和两个count
for n in nums:
if n == candidate1: //注意这里的元素值相等和count为0的判断顺序与问题一中正好相反
count1 += 1 //这里先判断元素值与candidate是否相等
elif n == candidate2:
count2 +=
elif count1 == : //再判断count是否为0
candidate1, count1 = n,
elif count2 == :
candidate2, count2 = n,
else:
count1, count2 = count1 - , count2 -
return [n for n in (candidate1, candidate2) if nums.count(n) > len(nums) // 3]

参考:segmentFault

Majority Element(169) && Majority Element II(229)的更多相关文章

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

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

  2. LeetCode Javascript实现 169. Majority Element 217. Contains Duplicate(两个对象比较是否相等时,如果都指向同一个对象,a==b才是true)350. Intersection of Two Arrays II

    169. Majority Element /** * @param {number[]} nums * @return {number} */ var majorityElement = funct ...

  3. LeetCode(169)Majority Element and Majority Element II

    一个数组里有一个数重复了n/2多次,找到 思路:既然这个数重复了一半以上的长度,那么排序后,必然占据了 a[n/2]这个位置. class Solution { public: int majorit ...

  4. 169. Majority Element 出现次数超过n/2的元素

    [抄题]: Given an array of size n, find the majority element. The majority element is the element that ...

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

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

  6. 【LeetCode】169. Majority Element 解题报告(Java & Python & C+)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 思路 hashmap统计次数 摩尔投票法 Moore ...

  7. 169. Majority Element(C++)

    169. Majority Element Given an array of size n, find the majority element. The majority element is t ...

  8. 23. leetcode 169. Majority Element

    169. Majority Element Given an array of size n, find the majority element. The majority element is t ...

  9. Leetcode#169. Majority Element(求众数)

    题目描述 给定一个大小为 n 的数组,找到其中的众数.众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素. 你可以假设数组是非空的,并且给定的数组总是存在众数. 示例 1: 输入: [3,2,3] ...

随机推荐

  1. android post 方式 访问网络 实例

    android post 方式 访问网络 实例 因为Android4.0之后对使用网络有特殊要求,已经无法再在主线程中访问网络了,必须使用多线程访问的模式 该实例需要在android配置文件中添加 网 ...

  2. [luogu4513]小白逛公园

    题目描述 在小新家附近有一条"公园路",路的一边从南到北依次排着n个公园,小白早就看花了眼,自己也不清楚该去哪些公园玩了. 一开始,小白就根据公园的风景给每个公园打了分-.-.小新 ...

  3. 【转】#pragma pack(push,1)与#pragma pack(1)的区别

    这是给编译器用的参数设置,有关结构体字节对齐方式设置, #pragma pack是指定数据在内存中的对齐方式. #pragma pack (n)             作用:C编译器将按照n个字节对 ...

  4. 【转】安全加密(二):BLE安全攻击反制措施

    本文导读 近年来出现了越来越多的低功耗蓝牙应用,即BLE(Bluetooth Low Energy),比如说智能手环.防丢器等,对蓝牙的安全要求也越来越高.这篇文章将深入浅出说明BLE4.0~4.2中 ...

  5. 洛谷 P4127 [AHOI2009]同类分布 解题报告

    P4127 [AHOI2009]同类分布 题目描述 给出两个数\(a,b\),求出\([a,b]\)中各位数字之和能整除原数的数的个数. 说明 对于所有的数据,\(1 ≤ a ≤ b ≤ 10^{18 ...

  6. 洛谷 P2725 邮票 Stamps 解题报告

    P2725 邮票 Stamps 题目背景 给一组 N 枚邮票的面值集合(如,{1 分,3 分})和一个上限 K -- 表示信封上能够贴 K 张邮票.计算从 1 到 M 的最大连续可贴出的邮资. 题目描 ...

  7. gcc编译器命令使用详解

    1.gcc包含的c/c++编译器gcc,cc,c++,g++,gcc和cc是一样的,c++和g++是一样的,(没有看太明白前面这半句是什么意思:))一般c程序就用gcc编译,c++程序就用g++编译 ...

  8. centos6.5之Hadoop1.2.1完全分布式部署安装

    0. 说明 系统中首先要安装好jdk环境. 已经配置ssh免密码登录. 设置好防火墙,或者关闭防火墙. 如果集群内机器的环境完全一样,可以在一台机器上配置好,然后把master配置好的软件即hadoo ...

  9. SQL Server 查

    注:where语句是条件,后面加and或者or 时间日期:比时间需要时间加引号 模糊查询:where语句后面加like  '%包含此关键字%'或者'以此关键字开头%'或者'%结尾' 排序查询:列名 o ...

  10. 百度地图BMapLib.InfoBox 手机兼容源码修改

    InfoBox.prototype.initialize = function (map) { var me = this; var div = this._div = baidu.dom.creat ...