LeetCode--Majority Element II & 多数投票算法
来源:互联网 发布:索尼手机无法连接网络 编辑:程序博客网 时间:2024/06/07 15:02
题目
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.
相似题目及多数投票算法
第一眼看到这个题,相信许多人都恩给你联想到另一个题目:
给定一个整数数组,找出出现次数大于 n/2 的那个数。
如果是找出出现次数大于n/2的数,解决这个问题的思路并不难,可以用Map扫描一遍,并且统计出现次数。但是这种方法的时间复杂度虽然是O(N),空间复杂度也相应的是O(N)。还有一种方法是多数投票算法,算法的名字虽然没听说过,但是思路相信大多数人还是知道的。
- 如果count==0,则将now的值设置为数组的当前元素,将count赋值为1;
- 反之,如果now和现在数组元素值相同,则count++,反之count–;
- 重复上述两步,直到扫描完数组。
之前做过的题目都是确定数组中有大于n/2的那个数存在的,所以没有了后边的检查步骤。
思路
看到这题首先想到的是出现次数大于⌊ n/3 ⌋
的数不只有一个,思考了一下,这个数最多有两个,最少一个也没有。所以可以用一个大小为2的数组保存候选结果,最后进行筛选。
然后是候选结果的保存,考察答题者的知识迁移能力,可怜的是我迁移了半天也没移对-,-
这里不说我的错误思路了。直接说解题方法吧。
以nums = [8,8,7,7,7]为例
一行跟第二行的0是默认初始化的值
代码
public class Solution { public List<Integer> majorityElement(int[] nums) { List<Integer> result = new ArrayList<Integer>(); if(nums == null || nums.length == 0){ return result; } int[] numbers = new int[2]; int[] count = new int[2]; for(int i = 0 ; i < nums.length ; i++){ if(count[0] == 0){ numbers[0] = nums[i]; }else if(count[1] == 0 && numbers[0] != nums[i]){ numbers[1] = nums[i]; } if(numbers[0] == nums[i]){ count[0]++; }else if(numbers[1] == nums[i]){ count[1]++; }else{ count[0]--; count[1]--; } } count[0] = count[1] = 0; for(int i = 0 ; i < nums.length ; i++){ for(int j = 0 ; j < numbers.length ; j++){ if(nums[i] == numbers[j]){ count[j]++; } } } if(count[0] > nums.length / 3) result.add(numbers[0]); if(count[1] > nums.length / 3 && numbers[1] != numbers[0]) result.add(numbers[1]); return result; }}
至于最后这一句
if(count[1] > nums.length / 3 && numbers[1] != numbers[0])
为什么要判断numbers[1] != numbers[0]
,是因为开始的时候初始化为0,要考虑都为0的情况。
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
- Android问题集锦
- Delphi CheckGroup
- 导入WeiboSDK和WeiboSDKDemo工程时,出现感叹号和红色叉叉的解决方案
- 如何正确高效使用搜索引擎
- Android--混淆
- LeetCode--Majority Element II & 多数投票算法
- 1193_分配座位问题
- python转化exe工具 py2exe 0.6.9.win32-py2.7
- 强密码的正则
- Oracle 正则表达式 regexp_like
- Android studio 打jar包
- C/C++头文件一览
- [LeetCode][Java] Valid Number
- Linux全栈工程师--传智播客C++公开课之全栈工程师修成记