leetcode---Majority Element
来源:互联网 发布:电脑防火墙软件 编辑:程序博客网 时间:2024/04/30 16:00
这道题有多个解法,贴出一位博主的图:
下面贴出我自己写的几种代码,其中思路二借鉴了一位博主的思想:http://www.cnblogs.com/ganganloveu/p/4177690.html
思路一:对数组先排序,这样相同的元素相邻,就很容易找到majority element了。
class Solution {public: int majorityElement(vector<int>& nums) { sort(nums.begin(),nums.end()); int coun=1,the_ele=nums[0]; int n=nums.size()/2; for(int i=1;i<nums.size();i++){ if(nums[i]!=nums[i-1]){ coun=1; continue; } else{ coun++; if(coun>n){ the_ele=nums[i]; break; } } } //cout<<the_ele<<endl; return the_ele; }};
思路二:每两个不同的元素看作一个组,把每个这样的组删除后剩下的一定是majority element 。
class Solution {public: int majorityElement(vector<int>& nums) {//每两个不同的元素就删除,剩下的那个就是majority element int can; int coun=0; for(int i=0;i<nums.size();i++){ if(coun==0){ can=nums[i]; coun=1; } else{ if(can==nums[i]) coun++; else coun--; } } return can; }};
思路三:对元素进行位运算,所有元素在每个二进制位上是1的数目多还是0的数目多,数目多的就决定了majority element在那个二进制位上是0还是1 。
class Solution {public: int majorityElement(vector<int>& nums) { int bit=0,re=0; int n=nums.size(); for(int i=0;i<32;i++){ for(int j=0;j<n;j++){ bit+=(nums[j]>>i)&1; } if(n-bit>bit) bit=0; else bit=1; re|=bit<<i; bit=0; } //cout<<re<<endl; return re; }};
0 0
- 【leetcode】Majority Element II,Majority element algorithm
- Leetcode: Majority Element &Majority Element II
- Leetcode Majority Element
- leetcode 169-Majority Element
- 【leetcode 哈希表】Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- leetcode: Majority Element
- [LeetCode] Majority Element
- leetcode 153: Majority Element
- leetcode Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- [LeetCode] Majority Element
- Leetcode-Majority Element
- [leetcode]Majority Element
- [LeetCode]Majority Element
- Leetcode: Majority Element
- android中MVP模式的小案例(一)
- 7CSS动画-2D、3D转换,过滤,动画,多列以及用多列实现瀑布流
- 15电气郄慧敏vb作业715个数的大小排序
- 菜鸟成长记-MFMessageComposeViewController的使用
- android Studio 使用技巧
- leetcode---Majority Element
- 在windows(64)下安装php开发环境wamp+yaf框架+phpstorm以及TortoiseGit
- 数据结构学习笔记(一)
- scala(1) 函数 条件表达式 循环
- linux网络
- UVA 11100(p81)----The Trip, 2007
- hdoj 2028Lowest Common Multiple Plus
- myisam和innodb索引实现的不同
- error c4996