【leetcode】169. Majority Element

来源:互联网 发布:中国 境外旅游 数据 编辑:程序博客网 时间:2024/05/29 13:16

题目:

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.

翻译:

假设数组中有一个数字的出现次数超过了数组元素个数的一半( ⌊ nums.size()/2 ⌋),找出这个数字并且返回这个值。

思路:

网上有思路说把数组内两两不同的元素就成对删除,最后剩下的就是需要找的元素,这个思路是可以的。我的想法比较简单,就是用哈希表记录每个元素出现的次数,这样遍历一遍数组即可。时间复杂度O(n),空间复杂度O(n)。

代码:

class Solution {public:int majorityElement(vector<int>& nums) {if (nums.size()==1){return nums[0];}int t_times=floor((double)nums.size()/2);map<int,int> result;for (int i=0;i<nums.size();i++){if (!result.count(nums[i])){result.insert(pair<int,int>(nums[i],1));}else{if(++result[nums[i]]>t_times)return nums[i];}}}};

结果:


0 0
原创粉丝点击