[leetcode]解决Majority Element的一点小心得
来源:互联网 发布:织梦cms本地安装教程 编辑:程序博客网 时间:2024/05/26 22:59
本次选择的题目是
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_mapclass 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]解决Majority Element的一点小心得
- [leetcode]解决Kth Largest Element in an Array的一点小心得
- [leetcode]解决Clone Graph的一点小心得
- [leetcode]解决Minimum Height Trees的一点小心得
- [leetcode]解决Same Tree的一点小心得
- [leetcode]解决Symmetric Tree的一点小心得
- [leetcode]解决Assign Cookies的一点小心得
- [leetcode]解决Move Zeroes的一点小心得
- [leetcode]解决Maximum Subarray的一点小心得
- [leetcode]解决Climbing Stairs的一点小心得
- [leetcode]解决House Robber的一点小心得
- OOA的一点小心得!
- github的一点小心得
- 使用开发工具的一点小心得
- 使用__doPostBack函数的一点小心得
- 调试VC++程序的一点小心得
- 关于系统设计的一点小心得
- 关于js的一点小心得
- SSM整合
- 2018年搜狗秋招前端笔试题:字符串删除
- CodeForces
- CSS经典布局-圣杯布局和双飞翼布局对比
- epoll模型
- [leetcode]解决Majority Element的一点小心得
- visual studio 2017搭建linux c++开发环境
- 1125. Chain the Ropes (25)
- 构造函数(构造器)
- 前行
- 求直线(线段)与直线(线段)的交点
- 淘宝网页价格爬虫
- HttpClient之接口测试
- HashMap和Hashtable的区别