[leetcode]解决Majority Element的一点小心得
2017-09-09 20:00
225 查看
本次选择的题目是
Majority Element 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.
1.解决这个问题最直接的方法是构造映射,将数字与出现次数对应起来,但问题是数组不能涵括无限的样例,所以这里采用map方法,这里我使用了
unordered_map和map类似,都是存储的key-value的值,可以通过key快速索引到value。
不同的是unordered_map不会根据key的大小进行排序,存储时是根据key的hash值判断元素是否相同,即unordered_map内部元素是无序的,而map中的元素是按照二叉搜索树存储,进行中序遍历会得到有序遍历。
所以使用时map的key需要定义operator<。而unordered_map需要定义hash_value函数并且重载operator==。但是很多系统内置的数据类型都自带这些,那么如果是自定义类型,那么就需要自己重载operator<或者hash_value()了。
结论:如果需要内部元素自动排序,使用map,不需要排序使用
2.使用Divide and Conquer,不断二分数组,统计每个小数组的majority。
Majority Element 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.
1.解决这个问题最直接的方法是构造映射,将数字与出现次数对应起来,但问题是数组不能涵括无限的样例,所以这里采用map方法,这里我使用了
unorder_map的特性。
unordered_map和map类似,都是存储的key-value的值,可以通过key快速索引到value。
不同的是unordered_map不会根据key的大小进行排序,存储时是根据key的hash值判断元素是否相同,即unordered_map内部元素是无序的,而map中的元素是按照二叉搜索树存储,进行中序遍历会得到有序遍历。
所以使用时map的key需要定义operator<。而unordered_map需要定义hash_value函数并且重载operator==。但是很多系统内置的数据类型都自带这些,那么如果是自定义类型,那么就需要自己重载operator<或者hash_value()了。
结论:如果需要内部元素自动排序,使用map,不需要排序使用
unordered_map class Solution { public: int majorityElement(vector<int>& nums) { unordered_map<int, int> counts; int n = nums.size(); for (int i = 0; i < n; i++) if (++counts[nums[i]] > n / 2) return nums[i]; } };
2.使用Divide and Conquer,不断二分数组,统计每个小数组的majority。
class Solution { public: int majorityElement(vector<int>& nums) { return majority(nums, 0, nums.size() - 1); } int majority(vector<int>& nums, int left, int right) { //递归的边界条件 if (left == right) return nums[left]; int mid = left + ((right - left) >> 1); int lm = majority(nums, left, mid); int rm = majority(nums, mid + 1, right); if (lm == rm) return lm; int l_m = count(nums.begin() + left, nums.begin() + right + 1, lm); int r_m = count(nums.begin() + left, nums.begin() + right + 1, rm); return l_m > r_m ? lm : rm; } };
相关文章推荐
- [leetcode]解决Clone Graph的一点小心得
- [leetcode]解决Kth Largest Element in an Array的一点小心得
- [leetcode]解决Climbing Stairs的一点小心得
- [leetcode]解决House Robber的一点小心得
- [leetcode]解决Minimum Height Trees的一点小心得
- [leetcode]解决Symmetric Tree的一点小心得
- [leetcode]解决Search a 2D Matrix II的一点小心得
- [leetcode]解决Same Tree的一点小心得
- [leetcode]解决Assign Cookies的一点小心得
- [leetcode]解决Burst Balloons的一点小心得
- [leetcode]解决Move Zeroes的一点小心得
- [leetcode]解决Maximum Subarray的一点小心得
- 解决Dynamips使用时CPU占用率100%的一点个人心得
- 系统很慢一点解决心得
- CGAL配置的一点心得(各种错误的解决办法)
- 关于信号槽连接地方的一点心得,一个问题困扰了一下午才解决,纪念一下。
- 解决堆损坏的一点心得
- 在Linux下串口信息的读取有了一点心得体会
- C++中有关const的一点心得
- 做leetcode时的一点小发现