Majority Number 解题报告
来源:互联网 发布:网络电话源码 编辑:程序博客网 时间:2024/05/16 12:02
Majority Number
Description
Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.
It should support push, pop and min operation all in O(1) cost.
Notice
You may assume that the array is non-empty and the majority number always exist in the array.
Example
Given [1, 1, 1, 1, 2, 2, 2], return 1
实现思路
这道题基于投票算法,
我们先假设数组nums中第一个数nums[0]就是我们要找的数vote,同时维护一个count变量,在后面判断中,如果nums[i] == vote(i=1….nums.length-1),则count++,如果不等,分两种情况:
1. 如果count > 0,则count–
2. 如果count = 0,则更新vote = nums[i]
为什么这样能得到我们要求的数major?我们可以这样分析:
对于任意一个数组nums中不等于major的数,基于我们的算法,它最终一定会被替换。因为它们的count(不超过一半)必定会在major(count大于一半)的不等判断下,被替换
那major会不会被替换呢?可能中间过程会,但遍历到最后,留下的必定是major。
根据此思路,求解方法如下:
java实现
public class Solution { /** * @param nums: a list of integers * @return: find a majority number */ public int majorityNumber(ArrayList<Integer> nums) { // write your code int vote = nums.get(0); int count = 1; for(int i = 1 ; i < nums.size(); i ++){ if(nums.get(i) == vote){ count ++; }else if(count == 0){ vote = nums.get(i); }else{ count --; } } return vote; }}
python实现
class Solution: """ @param nums: A list of integers @return: The majority number """ def majorityNumber(self, nums): # write your code here if not nums: return None vote = nums[0] count = 0 for num in nums: if num == vote: count += 1 elif count == 0: vote = num else: count -= 1 return vote
0 0
- Majority Number 解题报告
- LeetCode-Majority Element -解题报告
- 【LeetCode】Majority Element 解题报告
- Missing Number解题报告
- LeetCode-Majority Element II-解题报告
- [leetcode] 229. Majority Element II 解题报告
- [leetcode] 169. Majority Element 解题报告
- Leetcode解题报告:169. Majority Element
- LeetCode解题报告 169. Majority Element [easy]
- LeetCode 169. Majority Element 解题报告
- 【LeetCode】169. Majority Element解题报告
- [Leetcode] 169. Majority Element 解题报告
- 【LeetCode】229.Majority Element II解题报告
- [Leetcode] 229. Majority Element II 解题报告
- Friend Number ZOJ 解题报告
- POJ1423 Big Number解题报告
- HDU1212 Big Number 解题报告
- [LeetCode]Palindrome Number,解题报告
- MySQL命令行查询乱码解决方法
- 逆元相关
- static
- Making the Grade POJ 3666 求非严格递减的序列最小值
- kafka 指定partition两种方式&Consumer不消费消息的几个原因
- Majority Number 解题报告
- java之final关键字、包、封装
- 说一说本人对linux系统学习的方法和经验
- 新路程------uart驱动和tty(2)
- 移植QT-MYSQL到ARM(客户端版和完整版)
- Activity转场动画
- [Leetcode] 145. Binary Tree Postorder Traversal 解题报告
- 再议字符集和编码
- CodeForces