leetcode 169 Majority Element
2016-06-18 16:17
429 查看
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
class Solution {
public:
int majorityElement(vector<int> &nums) {
int temp = 0, cnt = 0;
for(int i = 0; i < nums.size(); i++) {
if(i == 0) {
temp = nums[i];
cnt += 1;
} else {
if(nums[i]!=temp) {
cnt-=1;
if(cnt==0) {
cnt = 1;
temp = nums[i];
}
}else {
cnt += 1;
}
}
}
return temp;
}
}
⌊ 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
class Solution {
public:
int majorityElement(vector<int> &nums) {
int temp = 0, cnt = 0;
for(int i = 0; i < nums.size(); i++) {
if(i == 0) {
temp = nums[i];
cnt += 1;
} else {
if(nums[i]!=temp) {
cnt-=1;
if(cnt==0) {
cnt = 1;
temp = nums[i];
}
}else {
cnt += 1;
}
}
}
return temp;
}
}
相关文章推荐
- ios method swizzling
- 最短路径 啊哈算法读书笔记
- jQueryMobile控件之按钮
- Django中ImageField的使用
- Java sun.misc.Unsafe
- Retrofit与RxAndroid结合使用
- 给基于Eclipse的ADT安装TFS插件
- jQueryMobile控件之复选框
- 转载——卷积神经网络(CNN)基础入门介绍
- 纸上谈兵: 树, 二叉树, 二叉搜索树
- 对于C++中traits的简单介绍
- EXT客户端panel上次打开时的状态(本地保存列隐藏、顺序、列宽、窗口大小)
- iOS给分类添加属性时使用 @selector()原理详解
- Android Scroll分析(二)——滑动的几种方法
- UVA11478 二分
- linux程序包管理2
- Problem E: C语言习题 矩形法求定积分
- Keil(MDK-ARM)使用教程(三)_在线调试
- w25q128 优化读写函数
- qt对话框