LeetCode 169. Majority Element
来源:互联网 发布:会计软件有哪些 编辑:程序博客网 时间:2024/05/30 22:56
问题:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
找出当前数组中出现的次数最多的,其中最多的那个数出现的次数一定超过[n/2].
问题分析:
这个这个问题如果用一般的方法做就是先用一个Map统计出每个数值出现的次数,然后找出最大的那一个。
但是这个问题中添加了一个额外的条件是 出现最多的数出现的次数超过了[n/2].
这样就有一种额外的解法:
找出两个不同的数都减一,知道最后剩下的哪个数。由于出现最多的数出现的次数超过了[n/2].那么无论如何排列进行减,最终留下的一定是出现最多的哪个数。
代码实现:
if (nums == null || nums.length == 0) { return 0; } int maxCount = 0; int num = -1; for (int i = 0; i < nums.length; i++) { if (maxCount == 0) { num = nums[i]; maxCount = 1; } else if (num != nums[i]) { maxCount--; } else { maxCount++; } } return num;
正常解法是先统计,然后进行找出出现次数最多的解法 。这里用了一种做减法的思路,同时由于有了>[n/2]这个条件使得这种实现变得正常。
阅读全文
0 0
- [LeetCode]169.Majority Element
- LeetCode 169.Majority Element
- 【LeetCode】169.Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- [leetcode] 169.Majority Element
- Leetcode 169. Majority Element
- 【LeetCode】169. Majority Element
- [LeetCode]169. Majority Element
- 169. Majority Element LeetCode
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- Leetcode 169. Majority Element
- [LeetCode]169. Majority Element
- 【LeetCode】169. Majority Element
- leetcode 169. Majority Element
- leetcode 169. Majority Element
- [leetcode] 169. Majority Element
- redis requires Ruby version -= 2.2.2问题
- Matlab_求最大特征值和特征向量
- SQLite3的简单使用
- 算法基础-->树
- C语言第七课
- LeetCode 169. Majority Element
- 蓝牙扫描器的隐患和双芯片握手协议
- lmathlib.c解析(5.3.4)
- 【牛客】顺时针打印矩阵
- C语言第八课
- 数据可视化工具
- 海思Hi3518EV200(5)图像sensor驱动开发
- zabbix 网络监控 -- 服务端的配置
- 利用css与html生成瀑布流图片展示