LeetCode--Majority Element II & 多数投票算法
来源:互联网 发布:Ubuntu chrome设置中文 编辑:程序博客网 时间:2024/05/24 02:07
这个题目与另外一个题目很相似:Majority Element:给定一个整数数组,找出出现次数大于 n/2 的那个数。
如果是找出出现次数大于n/2的数,解决这个问题的思路并不难,可以用Map扫描一遍,并且统计出现次数。但是这种方法的时间复杂度虽然是O(N),空间复杂度也相应的是O(N)。还有一种方法是多数投票算法,算法的名字虽然没听说过,但是思路相信大多数人还是知道的。
- 如果count==0,则将now的值设置为数组的当前元素,将count赋值为1;
- 反之,如果now和现在数组元素值相同,则count++,反之count–;
- 重复上述两步,直到扫描完数组。
这道题目就是迁移为两个majority,代码如下:
public class MajorityElementII {// boyer-moore majority vote algorithm public List<Integer> majorityElement(int[] nums) { int counter1 = 0,counter2 = 0, maj1 = 0, maj2 = 0; for(int i=0;i<nums.length;i++){ if(maj1==nums[i]){ counter1++; }else if(maj2 == nums[i]) counter2++; else if(counter1==0){ maj1 = nums[i]; counter1 = 1; }else if(counter2==0){ maj2 = nums[i]; counter2 = 1; }else{ counter1--; counter2--; } } counter1 = counter2 = 0; for(int tmp : nums){ if(tmp == maj1) counter1++; else if(tmp == maj2) counter2++; } List<Integer> res = new ArrayList<Integer>(); if(counter1>nums.length/3) res.add(maj1); if(counter2>nums.length/3) res.add(maj2); return res; }}
0 0
- LeetCode--Majority Element II & 多数投票算法
- LeetCode--Majority Element II & 多数投票算法
- LeetCode:Majority Element I II 投票算法
- 【LeetCode】169. Majority Element (多数投票算法 & 算法迁移能力)
- leetcode 229. Majority Element II 摩尔投票法 Moore Voting
- Leetcode 169 - Majority Element(Moore投票算法)
- [LeetCode] Majority Element II
- [leetcode] Majority Element II
- #leetcode#Majority Element II
- 【LeetCode】Majority Element II
- LeetCode Majority Element II
- LeetCode - Majority Element II
- LeetCode Majority Element II
- leetcode: Majority Element II
- [LeetCode] Majority Element II
- leetcode--Majority Element II
- LeetCode-Majority Element II
- Leetcode: Majority Element II
- UI基础_自定义非等高Cell_storyboard封装_版本_有GIF_源代码
- Python案例-网络编程-I/O多路复用-select方法用例
- HDU 1251-统计难题
- android实现对PDF进行签名、涂鸦操作
- cookie与session详解
- LeetCode--Majority Element II & 多数投票算法
- size_t类型
- java 学习笔记2
- Android开发中如何结束所有的activity
- HDU Problem 1873 看病要排队 【优先队列】
- select函数详细解读
- python flask request params
- python 学习(十一)之字符串2
- lintcode binary-tree-maximum-path-sum 二叉树中的最大路径和