本文共 925 字,大约阅读时间需要 3 分钟。
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 for adding this problem and creating all test cases.
public class Solution { public int majorityElement(int[] num) { Map map = new HashMap(); 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; }}
转载地址:http://znuni.baihongyu.com/