169. Majority Element
2016-03-19 00:08
316 查看
1.Question
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.
2.Code
codeA
codeB
codeC
3.Note
a.写了三个版本的解法,leetcode上跑的时间分为别16ms,
36ms ,40ms.
codeA的空间复杂度为1,时间复杂度为n。所用思想为:占n/2以上的元素能够抵消剩下小于n/2的元素的数目,则candidate能保留着majorityElement.
codeB就是哈希表的思想,统计元素的个数,然后大于n/2时就输出对应的元素。
codeC需要先排序,思想是占n/2的元素在全集中的长度大于n/2,则能保证nums[i]=nums[i+n/2],再遍历一遍就可以找出来。但是排序消耗时间。
可以得出,codeA是最优的解法。
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.
2.Code
codeA
class Solution { public: int majorityElement(vector<int>& nums) { int candidate = 0, count = 0; for(int i = 0; i < nums.size(); i++) { if(count == 0) { count = 1; candidate = nums[i]; } else if(candidate == nums[i]) count++; else count--; } return candidate; } };
codeB
class Solution { public: int majorityElement(vector<int>& nums) { unordered_map <int, int> map; int n = nums.size(); if(n == 1) return nums[0]; for(int i = 0; i < n; i++) { if(map.find(nums[i]) != map.end()) { if(++map[nums[i]] > n/2) return nums[i]; } else { map[nums[i]] = 1; } } } };
codeC
class Solution { public: int majorityElement(vector<int>& nums) { int n = nums.size(); if(n == 1) return nums[0]; sort(nums.begin(), nums.end()); for(int i = 0; i < n; i++) { if(nums[i] == nums[i + n/2]) return nums[i]; } } };
3.Note
a.写了三个版本的解法,leetcode上跑的时间分为别16ms,
36ms ,40ms.
codeA的空间复杂度为1,时间复杂度为n。所用思想为:占n/2以上的元素能够抵消剩下小于n/2的元素的数目,则candidate能保留着majorityElement.
codeB就是哈希表的思想,统计元素的个数,然后大于n/2时就输出对应的元素。
codeC需要先排序,思想是占n/2的元素在全集中的长度大于n/2,则能保证nums[i]=nums[i+n/2],再遍历一遍就可以找出来。但是排序消耗时间。
可以得出,codeA是最优的解法。
相关文章推荐
- Java中如何中断线程?
- android点击事件分发
- leshi
- 软件测试 HW3 Lab1
- 1078. Hashing (25)【Hash + 探测】——PAT (Advanced Level) Practise
- Spark standalone 模式下的集群部署
- 熟悉Eclipse开发工具
- 2016春季练习——水题排序小贪心
- JAVA面向对象之接口
- 查看手机SD卡视频音频文件信息
- android 权重
- 指针与数组【重学C之五】
- 每日安全资讯:研究人员发现能逃避杀毒软件检测的 Linux 后门
- Rust 1.35 发布,及Rust升级方法
- Android五种数据存储方式
- Java微信公众平台开发(13) 微信JSSDK中Config配置
- 使用Python编写基于DHT协议的BT资源爬虫
- Python的Socket编程过程中实现UDP端口复用的实例分享
- FleaPHP框架数据库查询条件($conditions)写法总结
- smarty学习笔记之常见代码段用法总结