leetcode Majority Element

题目连接

https://leetcode.com/problems/majority-element/  

Majority Element

Description

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.

class Solution {
	typedef unordered_map<int, int> UMAP;
public:
	int majorityElement(vector<int>& nums) {
		UMAP mp;
		int ans = 0, n = (int)nums.size();
		for (auto &r : nums) { mp[r]++; }
		for (auto &r : mp) {
			if (r.second > n / 2) {
				ans = r.first; 
			}
		}
		return ans;
	}
};
posted @ 2015-12-09 19:56  GadyPu  阅读(114)  评论(0编辑  收藏  举报