LeetCode OJ刷题历程——Majority Element
2016-04-03 22:04
309 查看
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.
以上为题目要求,下面贴出代码:
class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(),nums.end()); if(nums.size() == 1) return nums[0]; int length = nums.size()/2 == 0?nums.size()/2 : nums.size()/2 +1; for(int i = 0;i<length;i++) if(nums[i] == nums[i+length-1]) return nums[i]; } };40ms
class Solution { public: int majorityElement(vector<int>& nums) { stack<int>s; for(auto n : nums){ if(s.empty() || n == s.top()) s.push(n); else s.pop(); } return s.top(); } };24ms
class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(),nums.end()); int index = nums[0]; int count = 1; for(int i = 1;i<nums.size();i++){ if(index == nums[i]) count++; else{ if(count > nums.size()/2) return index; else{ index = nums[i]; count == 1; } } } return index; } };40ms
其中第三种方法比较容易想到,下面分析第一、二种方法
第一种对nums进行排序,因为如果是众数的话,其个数必定大于nums.size()的一半,所以如果nums[i] == nums[i+length/2 -1],那必定是众数
第二种是利用栈来进行判断,遇到不一样的数就进行弹栈操作,一样的入栈操作,如果不是众数,那么必定有多余其个数的数与之不同,那么栈中必定不会保留此数。
相关文章推荐
- 局域网的概括
- 10.字符设备控制学习
- CentOS 7.1编译安装PHP7
- linux网络
- HDU 1114 Piggy-Bank(完全背包/二进制压缩orO(V*N)算法)
- 数据结构实验2-1
- [Queue]——面向接口编程
- 3.0-saltstack几个常用的命令
- 实体类和JSON对象之间相互转化
- 一道有趣的数学题
- 2.9-saltstack管理任务计划
- KNN算法 C++实现
- 2.8-saltstack远程执行shell脚本
- Cassandra教程(6)---- Snitch
- 一种可以避免数据迁移的分库分表scale-out扩容方式
- workbench导入 非agdb格式文件,拉伸时无imprint faces 这一项问题解决方法
- gcc命令
- 【转】java代码中实现android背景选择的selector-StateListDrawable的应用
- 2.7-saltstack远程执行命令
- 2.6-saltstack文件和目录管理