【LeetCode】229. Majority Element II 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/majority-element-ii/description/
题目描述
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]
题目大意
找出一个数组中出现次数超过⌊ n/3 ⌋次的所有数字。
解题方法
hashmap统计次数
虽然不符合题目的要求,但是一般情况下,对空间复杂度要求的题目都不用管它的空间要求。这样很快就能写出来。
时间复杂度是O(N),空间复杂度是O(N)。
Python代码如下:
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
N = len(nums)
count = collections.Counter(nums)
res = []
for n, t in count.items():
if t > N / 3:
res.append(n)
return res
C++代码如下:
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
const int N = nums.size();
unordered_map<int, int> count;
for (int n : nums)
++count[n];
vector<int> res;
for (auto& c : count) {
if (c.second > N / 3) {
res.push_back(c.first);
}
}
return res;
}
};
摩尔投票法 Moore Voting
题目要求的是线性时间和常量的空间,和169. Majority Element基本一样的。169题使用一次遍历就找出了超过出现次数超过一半的数字。这个题需要在这个基础上更进一步。首先我们肯定知道数组中出现次数超过⌊ n/3 ⌋次的最多有两个!因为如果3个的话,这三个数字的总次数 > 3×⌊ n/3 ⌋ = n,不可能的。所以我们对这个题的做法同样使用摩尔投票法,先使用两个变量分别保存次数最多和次多的就可以了。然后我们还需要再过一遍数组,判断次数最多和次多的是不是超过了⌊ n/3 ⌋次,把超过的数字返回就行了。
踩到的坑:
- 在第一个for循环中,必须先判断是不是已经和已有的相等,如果不满足的情况下才能判断是不是次数为0。比如题目中给的例子
[1,1,1,3,3,2,2,2],如果先判断cm和cn的次数是不是0,那么会把m和n分别都设置成了1。而我们的目的是m和n分别代表两个不同的数字,所以应该先做是不是和已有的数字相等的判断。 - 统计次数的时候需要用if 和else if,不能两个if。这个是因为我们把m和n都初始化成了0,对于
[0,0,0]这个测试用例,如果两个if会导致结果是[0,0]。
时间复杂度是O(N),空间复杂度是O(1)。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
N = len(nums)
m = n = cm = cn = 0
for num in nums:
if num == m:
cm += 1
elif num == n:
cn += 1
elif cm == 0:
m = num
cm = 1
elif cn == 0:
n = num
cn = 1
else:
cm -= 1
cn -= 1
cm = cn = 0
for num in nums:
if num == m:
cm += 1
elif num == n:
cn += 1
res = []
if cm > N / 3:
res.append(m)
if cn > N / 3:
res.append(n)
return res
C++代码如下:
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int m = 0, n = 0, cm = 0, cn = 0;
for (int i : nums) {
if (m == i) {
++cm;
} else if (n == i) {
++cn;
} else if (cm == 0) {
m = i;
cm = 1;
} else if (cn == 0) {
n = i;
cn = 1;
} else {
--cm;
--cn;
}
}
cm = cn = 0;
for (int i : nums) {
if (i == m)
++cm;
else if (i == n)
++cn;
}
vector<int> res;
const int N = nums.size();
if (cm > N / 3)
res.push_back(m);
if (cn > N / 3)
res.push_back(n);
return res;
}
};
相似题目
参考资料
http://www.cnblogs.com/grandyang/p/4606822.html
日期
2018 年 10 月 29 日 —— 美好的一周又开始了
【LeetCode】229. Majority Element II 解题报告(Python & C++)的更多相关文章
- [LeetCode] 229. Majority Element II 多数元素 II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. Note: The a ...
- 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 ...
- leetcode 229 Majority Element II
这题用到的基本算法是Boyer–Moore majority vote algorithm wiki里有示例代码 1 import java.util.*; 2 public class Majori ...
- LeetCode 229. Majority Element II (众数之二)
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorit ...
- leetcode 229. Majority Element II(多数投票算法)
就是简单的应用多数投票算法(Boyer–Moore majority vote algorithm),参见这道题的题解. class Solution { public: vector<int& ...
- (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 ...
- leetcode 169. Majority Element 、229. Majority Element II
169. Majority Element 求超过数组个数一半的数 可以使用hash解决,时间复杂度为O(n),但空间复杂度也为O(n) class Solution { public: int ma ...
- 【LeetCode】229. Majority Element II
Majority Element II Given an integer array of size n, find all elements that appear more than ⌊ n/3 ...
- 【刷题-LeetCode】229. Majority Element II
Majority Element II Given an integer array of size n, find all elements that appear more than ⌊ n/3 ...
随机推荐
- 漏洞分析:CVE-2017-17215
漏洞分析:CVE-2017-17215 华为HG532路由器的命令注入漏洞,存在于UPnP模块中. 漏洞分析 什么是UPnP? 搭建好环境(使用IoT-vulhub的docker环境),启动环境,查看 ...
- SCRDet——对小物体和旋转物体更具鲁棒性的模型
引言 明确提出了三个航拍图像领域内面对的挑战: 小物体:航拍图像经常包含很多复杂场景下的小物体. 密集:如交通工具和轮船类,在航拍图像中会很密集.这个DOTA数据集的发明者也提到在交通工具和轮船类的检 ...
- Linux学习 - 系统定时任务
1 crond服务管理与访问控制 只有打开crond服务打开才能进行系统定时任务 service crond restart chkconfig crond on 2 定时任务编辑 crontab [ ...
- 二叉树——Java实现
1 package struct; 2 3 interface Tree{ 4 //插入元素 5 void insert(int value); 6 //中序遍历 7 void inOrder(); ...
- Linux_spool命令
spool的作用是什么? spool的作用可以用一句话来描述:在sqlplus中用来保存或打印查询结果. 参数指南 对于SPOOL数据的SQL,最好要自己定义格式,以方便程序直接导入,SQL语句如: ...
- 【科研工具】CAJViewer的一些操作
逐渐发现CAJViewer没有想象中的难用. 添加书签:Ctrl+M 使用按类分类,可以筛选出书签位置,和注释区分. 搜索:Ctrl+F 可以定义多种搜索.
- 关于python中的随机种子——random_state
random_state是一个随机种子,是在任意带有随机性的类或函数里作为参数来控制随机模式.当random_state取某一个值时,也就确定了一种规则. random_state可以用于很多函数,我 ...
- minkube在deban10上的安装步骤
环境准备: 所用机器为4c 16g i3 4170 1t机械硬盘 系统 debian 10 安装docker 如果已经安装并配置好可直接跳过 安装ssl sudo apt-get install ...
- 对Spring IOC容器的思考
最近在看Spring5的视频教学,学到了IOC容器这块,对IOC有些浅薄的理解,分享一二:有错误之处,还请大佬指出 IOC(Inversion of Control 控制反转),是面向对象编程中的一种 ...
- mysql联合索引阻碍修改列数据类型:BLOB/TEXT column 'name' used in key specification without a key length
今天在项目中mysql表中有一个字段数据类型为varchar,长度不够需要换为text类型 当时表是已经存在的表, CREATE TABLE `table_aaa` ( `id` int NOT NU ...