Majority Element
来源:互联网 发布:金牛考勤软件电话 编辑:程序博客网 时间:2024/04/25 08:39
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.
Use Moore's voting.1. Use num[0] as the candidate, and maintain a counter of how many times this candidate shows
2. For each element, if it equals to candidate, count++; if it doesn't equal to candidate, either replace the candidate(count == 0) or count-- (count > 0)
3. In the end of the loop, the left candidate is the result.
public int majorityElement(int[] num) { int candidate = num[0]; int count = 1; for (int i = 1; i < num.length; i++) { if (num[i] == candidate) { count++; } else { if (count == 0) { candidate = num[i]; count = 1; } else { count--; } } } return candidate; }
0 0
- majority element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- majority element
- Majority Element
- Majority Element
- 入门训练 圆的面积
- 14_android进度条对话框的使用说明
- 红黑树深入浅出
- 获取NGUI的输入框内容的方法
- 几款不错的VisualStudio2010插件
- Majority Element
- C#实现MD5加密
- 突出 醒目
- [leetcode]Excel Sheet Column Title
- 将一个数的二进制位进行翻转
- 入门训练 序列求和
- A. Minimum Difficulty
- 见与不见
- ubuntu 12.04下gedit查看txt中文乱码解决办法