Majority Element

来源:互联网 发布:耽美小说完结推荐知乎 编辑:程序博客网 时间:2024/03/28 21:57

Majority Element

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.

Java代码:

public class Solution {    public int majorityElement(int[] num) {        Map map = new HashMap<Integer, Integer>();int tmp = 0;for (int i = 0; i < num.length; i++) {if (!map.containsKey(num[i])) {map.put(num[i], 1);} else {tmp = (Integer) map.get(num[i]);tmp = tmp + 1;map.put(num[i], tmp);}}tmp = 0;int val = 0;int key = 0;Iterator ite = map.entrySet().iterator();while (ite.hasNext()) {Map.Entry entry = (Map.Entry) ite.next();val = (Integer) entry.getValue();if (val > tmp) {tmp = val;key = (Integer) entry.getKey();}}return key;    }}


0 0