博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LeetCode】169. Majority Element 解题小结
阅读量:4649 次
发布时间:2019-06-09

本文共 941 字,大约阅读时间需要 3 分钟。

题目: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.

Credits:

自己的思路大概是建立一个map,key对应数字,value对应数字出现的次数,然后比较次数最多的那个应该就是Majority Element。

class Solution {public:    unordered_map
map; int majorityElement(vector
& nums) { int indexMax; for (int i = 0; i < nums.size(); i++) { if (map.find(nums[i]) == map.end()) { map[nums[i]] = 1; } else { map[nums[i]]++; } } indexMax = 0; for (int i = 1; i < nums.size(); i++) { if (map[nums[i]] > map[nums[indexMax]] && map[nums[i]] >= map.size() / 2) indexMax = i; } return nums[indexMax]; }};

 

转载于:https://www.cnblogs.com/Doctengineer/p/5798955.html

你可能感兴趣的文章