标签:
题目: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<int, int> map; int majorityElement(vector<int>& 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]; } };
【LeetCode】169. Majority Element 解题小结
标签:
原文地址:http://www.cnblogs.com/Doctengineer/p/5798955.html