169. Majority Element
2016-07-02 10:29
369 查看
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.
Credits:
Special thanks to
@ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
思路:
超过一半的数,开始记为0位置上的数,以后每遇到一个相同的,则计数+1;若不相同则计数-1;计数为0 则取当前的。因为major超过一半,因此会抵消掉其他数,最后剩下的就是major.
代码:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int major=nums[0];
int c=1;
for(int i=1;i<nums.size();++i)
{
if(c==0)
{major=nums[i];c=1;}
else if(major==nums[i])
c++;
else
c--;
}
return major;
}
};
more than
⌊ n/2 ⌋times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to
@ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
思路:
超过一半的数,开始记为0位置上的数,以后每遇到一个相同的,则计数+1;若不相同则计数-1;计数为0 则取当前的。因为major超过一半,因此会抵消掉其他数,最后剩下的就是major.
代码:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int major=nums[0];
int c=1;
for(int i=1;i<nums.size();++i)
{
if(c==0)
{major=nums[i];c=1;}
else if(major==nums[i])
c++;
else
c--;
}
return major;
}
};
相关文章推荐
- 实时数据显示
- synchronized的详解
- Digits'path
- 基于Node的PetShop,RESTful API以及认证
- Thingking in Java 源代码导入
- 摄像机标定终极总结版01
- dd error: resource busy
- /boot空间不足
- TCP/IP详解学习笔记(1)-基本概念
- IO中同步、异步与阻塞、非阻塞的区别
- Ubuntu下提示/boot空间不足解决办法
- oracle数据库中查询一个表中的字段是否存在于另一个表中字段数据
- 6.5、Android Studio的Android Device Monitor
- 6.5、Android Studio的Android Device Monitor
- linux命令目录
- VIM 命令速查卡
- IntelliJ IDEA 常用设置讲解
- 关于大小端模式的浅淡
- IntelliJ IDEA 常用设置讲解
- SSH免密码登录的配置