题意:
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
时间: 2024-10-21 04:43:57