标签:
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.
在数组中找出出现次数大于 n/2 的数。
C++ 中map 对于这种统计次数的问题来说特别方便,而 Python 的话当然用字典。
C++
class Solution{
public:
int majorityElement(vector<int> &num) {
vector<int>::iterator it = num.begin();
int n = num.size();
map<int,int> count;
for(;it != num.end();it++)
{
// 这里为什么不用判断键是否存在?因为不存在时初始化为 0
if(++count[*it] > n/2)
{
return *it;
}
}
}
};
Python:
class Solution:
# @param num, a list of integers
# @return an integer
def majorityElement(self, num):
count = dict([])
flag = len(num)/2
for item in num:
if item in count:
count[item] = count[item] + 1
else:
count[item] = 1
if count[item] > flag:
return item标签:
原文地址:http://blog.csdn.net/jcjc918/article/details/43926577