[LeetCode]169. Majority Element寻找数组中超过一半的那个数
2016-09-18 22:15
489 查看
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
每找出两个不同的element,就成对删除即count--,最终剩下的一定就是所求的。时间复杂度:O(n)
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int majorityElement(vector<int>& nums)
{
int n,count=0,len=nums.size();
for(int i=0;i<len;i++)
{
if(count==0)
{
count++;
n=nums[i];
}
else{
if(nums[i]==n)
count++;
else
count--;
}
}
return n;
}
int main()
{
vector<int> numbers;
numbers.push_back(1);
numbers.push_back(3);
numbers.push_back(3);
cout<<majorityElement(numbers)<<endl;
}
⌊ 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
每找出两个不同的element,就成对删除即count--,最终剩下的一定就是所求的。时间复杂度:O(n)
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int majorityElement(vector<int>& nums)
{
int n,count=0,len=nums.size();
for(int i=0;i<len;i++)
{
if(count==0)
{
count++;
n=nums[i];
}
else{
if(nums[i]==n)
count++;
else
count--;
}
}
return n;
}
int main()
{
vector<int> numbers;
numbers.push_back(1);
numbers.push_back(3);
numbers.push_back(3);
cout<<majorityElement(numbers)<<endl;
}
相关文章推荐
- 169. Majority Element--寻找数组中出现次数超过一半的数据,229. Majority Element II--注意最后的检测
- leetcode169---Majority Element(数组中出现次数超过一半的数)
- 169.Majority Element (数组中出现次数超过一半的数)
- ※ Leetcode - Array - 169. Majority Element(快速找出数组中出现过一半以上次数的数,3种写法)
- leetcode-169. Majority Element 寻找众数,hash方法
- [LeetCode169]Majority Element求一个数组中出现次数大于n/2的数
- [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
- 寻找发帖水王(找出数组出现超过一半的数字)
- 【算法22】寻找数组中出现次数超过一半的数字
- LeetCode 169. Majority Element
- LeetCode169 Majority Element
- [LeetCode][169][Majority Element]
- LeetCode 169 Majority Element