LeetCode Majority Element II(Moore Voting Algorithm即Majority Voting Algorithm)
来源:互联网 发布:如何购买域名 编辑:程序博客网 时间:2024/05/12 17:46
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/3的元素,要求时间复杂度为O(n),空间复杂度为O(1)
思路:用Majority Voting Algorithm的一般算法
1、候选者的个数为2,计数数组的元素个数也为2
2、在遍历时,如果候选者中没有包含,就将其插入,如果包含,将计数加1,如果没有包含,将所有候选者的计数减1
3、第二次遍历时,统计个数,判断出现次数是否满足要求
代码如下:
class Solution{ public List<Integer> majorityElement(int[] nums) { List<Integer> res = new ArrayList<Integer>(); if (nums.length == 0) return res; else return __majorityElement(nums, 3); } private List<Integer> __majorityElement(int[] nums, int k) { int cnt = k - 1; ArrayList<Integer> candidates = new ArrayList<Integer>(); ArrayList<Integer> count = new ArrayList<Integer>(); for (int i = 0; i < cnt; i++) { candidates.add(0); count.add(0); } for (int num : nums) { boolean found = false; for (int i = 0; i < cnt; i++) { if (count.get(i) == 0 || candidates.get(i) == num) { int c = count.get(i); count.set(i,c + 1); candidates.set(i, num); found = true; break; } } if (!found) { for (int i = 0; i < cnt; i++) { int c = count.get(i); count.set(i, c - 1); } } } Collections.fill(count, 0); for (int num : nums) { for (int i = 0; i < cnt; i++) { if (candidates.get(i) == num) { int c = count.get(i); count.set(i, c + 1); break; } } } List<Integer> ans = new ArrayList<Integer>(); for (int i = 0; i < cnt; i++) { if (count.get(i) > nums.length / k) { ans.add(candidates.get(i)); } } return ans; }}
0 0
- LeetCode Majority Element II(Moore Voting Algorithm即Majority Voting Algorithm)
- [LeetCode 169]Majority Element: Moore Voting Algorithm
- Majority Element解决:Moore's Voting Algorithm
- leetcode-169 Majority Element(Moore's voting algorithm)
- 153. Find Minimum in Rotated Sorted Array\229. Majority Element II\Moore's voting algorithm
- leetcode 229. Majority Element II 摩尔投票法 Moore Voting
- 【leetcode】Majority Element II,Majority element algorithm
- Moore's voting algorithm
- Moore’s voting algorithm
- Moore's voting algorithm
- Moore’s Voting Algorithm
- Moore's voting algorithm
- Moore's voting algorithm
- Moore's voting algorithm
- LeetCode 229 Majority Element II(主要元素II)(Array)(Boyer–Moore majority vote algorithm)
- Moore's majority vote algorithm
- The Boyer-Moore Majority Vote Algorithm
- Boyer–Moore majority vote algorithm
- Form表单中的action提交路径问题
- hdoj 连连看 1175 (bfs)
- strcpy,memset,memcpy区别
- SDUT 3019 电梯
- 三极管有哪几种工作状态?每种工作状态的工作条件?
- LeetCode Majority Element II(Moore Voting Algorithm即Majority Voting Algorithm)
- 温故知新: Java知识点终极列表(下)
- PowerPC简介
- 安卓解析XML并显示在ListView
- OC知识补充
- Redis应用场景 redis精髓
- mysql插入数据过大, Lost connection to MySQL server
- Object-c 对象的使用和定义
- Docker学习之简单介绍