cKK

............当你觉得自己很辛苦,说明你正在走上坡路.............坚持做自己懒得做但是正确的事情,你就能得到别人想得到却得不到的东西............

导航

(Array)169. Majority Element

Posted on 2016-04-11 23:49  cKK  阅读(117)  评论(0编辑  收藏  举报

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.

public class Solution {      //更好的方法是排序,return 中间那个数
    public int majorityElement(int[] nums) {
     	Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		for (int i = 0; i < nums.length; i++) {
			if (map.containsKey(nums[i])) {
				map.put(nums[i], map.get(nums[i])+1);
			} else
				map.put(nums[i], 1);
		}
		Set set = map.entrySet();
		Iterator it = set.iterator();
		int res = 0;
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			if ((int) entry.getValue() > nums.length / 2)
				res = (int) entry.getKey();
		}
		return res;
    }
    
}