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:

  1. If the counter is 0, we set the current candidate to x and the counter to 1.
  2. If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.

0 0
原创粉丝点击