leetcode 169 Majority Element
来源:互联网 发布:websocket java 案例 编辑:程序博客网 时间:2024/04/29 09:58
题目描述:
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.
本题非常简单,写出来主要是方便准备面试的同学,这道题在面试题中出现的概率十分高,所以这里说明一下思路。
O(nlogn)的算法很容易实现,排序一下基本就OK,但是这种思路并不满足面试官的要求,通常会要求O(n)的思路。
观察数组就会发现一个很有趣的现象,达到majority要求的元素,总会出现位置相邻的情况,我们利用这个特点,对数组进行遍历,即可得到最后的结果。
代码实现如下(C++11): class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 1;
if(nums.size()==0)
return 0;
int max = nums[0];
for(int i = 1;i<nums.size();i++) {
if(nums[i]==max) {
count++;
}else {
count--;
}
if(count<=0) {
max = nums[i];
count = 1;
}
}
if(count>0) {
count = 0;
for(auto&val:nums) {
if(val == max)
count++;
}
}
if(count>nums.size()/2)
return max;
return 0;
}
};
- leetcode 169-Majority Element
- [leetcode 169] Majority Element
- leetCode#169 Majority Element
- Leetcode-169Majority Element
- LeetCode 169: Majority Element
- [LeetCode][169][Majority Element]
- LeetCode 169 Majority Element
- Majority Element leetcode[169]
- Leetcode[169]-Majority Element
- leetcode[169]:Majority Element
- leetcode-169-Majority Element
- leetcode 169: Majority Element
- Leetcode # 169 Majority Element
- [Leetcode]#169 Majority Element
- LeetCode 169: Majority Element
- 【LEETCODE】169-Majority Element
- 【LeetCode】169Majority Element
- Leetcode #169 Majority Element
- angularjs与requirejs整合实用技巧
- 关于Floyd算法三重循环顺序的问题
- 分数加减法
- 测试
- 【DRP】笔记之JavaScript内置对象
- leetcode 169 Majority Element
- ps快捷键
- 机器视觉学习笔记--二值图像处理
- 歌曲《随缘》国语版
- Spring 拦截器配置——模糊路径的含义
- qt ros
- hdu 4734 F(x) 数位dp
- 关于 ant Design的分页组件的应用
- 解决Incorrect integer value: '' for column 'id' at row 1的方法