和大神们学习每天一题(leetcode)-Majority Element
2014-12-24 09:46
519 查看
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
本题楼主用的是哈希表的方法,根据数组中的元素建立哈希表,表中存有数组中的元素和它出现的次数,建表后查找出出现次数超过n/2的。
功能测试用例:{1,1,1,1,1,1,2,3,4,5}
特殊测试用例:{},{1}
⌊ n/2 ⌋times.
You may assume that the array is non-empty and the majority element always exist in the array.
本题楼主用的是哈希表的方法,根据数组中的元素建立哈希表,表中存有数组中的元素和它出现的次数,建表后查找出出现次数超过n/2的。
功能测试用例:{1,1,1,1,1,1,2,3,4,5}
特殊测试用例:{},{1}
class Solution { public: int majorityElement(vector<int> &num) { if (num.size() == 0) return NULL; map<int, int> mnnNum;//建立哈希表 for (int nTemp = 0; nTemp < num.size(); nTemp++) { if (mnnNum.count(num[nTemp])>0)//如果存在则次数加1 { mnnNum[num[nTemp]] += 1; } else { mnnNum.insert(pair<int, int>(num[nTemp], 1));//如果不存在则插入哈希表 } } map<int, int>::iterator mnniPoint; for (mnniPoint = mnnNum.begin(); mnniPoint != mnnNum.end(); mnniPoint++)//查找出哈希表中对应出现次数超过数组长度一半的 { if (mnniPoint->second > num.size() / 2) { return mnniPoint->first; } } return NULL; } };
相关文章推荐
- 和大神们学习每天一题(leetcode)-Add Binary
- 和大神们学习每天一题(leetcode)-Reverse Integer
- 和大神们学习每天一题(leetcode)-Balanced Binary Tree
- 和大神们学习每天一题(leetcode)-Remove Duplicates from Sorted List
- 和大神们学习每天一题(leetcode)-Remove Element
- 和大神们学习每天一题(leetcode)-Symmetric Tree
- 和大神们学习每天一题(leetcode)-Merge Two Sorted Lists
- 和大神们学习每天一题(leetcode)-Maximum Depth of Binary Tree
- 和大神们学习每天一题(leetcode)-Path Sum
- 和大神们学习每天一题(leetcode)-Climbing Stairs
- 和大神们学习每天一题(leetcode)-Sort Colors
- 和大神们学习每天一题(leetcode)-Intersection of Two Linked Lists
- 和大神们学习每天一题(leetcode)-ZigZag Conversion
- 和大神们学习每天一题(leetcode)-Minimum Depth of Binary Tree
- 和大神们学习每天一题(leetcode)-Pascal's Triangle
- 和大神们学习每天一题(leetcode)-Count and Say
- 和大神们学习每天一题(leetcode)-Binary Tree Level Order Traversal II
- 和大神们学习每天一题(leetcode)-Longest Common Prefix
- 和大神们学习每天一题(leetcode)-Merge Sorted Array
- 和大神们学习每天一题(leetcode)-Plus One