Majority Element
来源:互联网 发布:淘宝金牌卖家可以刷吗 编辑:程序博客网 时间:2024/04/25 19:58
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.
My solution:
1. My first thought is to solve this problem in a brute-force way, which means:
Create a HashMap<int, int>, the second int is the count of that integer in the array.
Code:
public int majorityElement(int[] num) {HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();for (int i = 0;i<num.length;i++){if(hm.containsKey(num[i])){int count = hm.get(num[i]);hm.put(num[i], count+1);}else{hm.put(num[i], 1);}}Iterator<Integer> itr = hm.keySet().iterator();while(itr.hasNext()){int key = itr.next();if(hm.get(key)>num.length/2)return key;} return 0; }
2. Optimal Method:
Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
- If the counter is 0, we set the current candidate to x and the counter to 1.
- If the counter is not 0, we increment or decrement the counter based on whether x is the current 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
- 【有图】android通过jdbc连接mysql(附文件)
- 当fscanf碰上nan
- String.valueOf(que[i]).getBytes()含义
- Tomcat的虚拟目录的创建步骤
- 插入数据获得主键,调用其他存储过程
- Majority Element
- 【poj1811】Miller_Rabin and Pollard_rho
- NC3.0 环境变量
- python 基础知识学习
- CenotOS6中文环境下安装Oracle 11g 中文乱码 解决办法
- 我今天又没吃药
- 输入10个数,找出出现次数最多的数 (如果多个并列,则按数字出现顺序分别输出)
- Maven解决Missing artifact com.sun:tools:jar:1.5.0错误
- 一个由c/C++编译的程序占用的内存分几个部分