[Leetcode]Majority Element II
2015-08-21 10:58
211 查看
Given an integer array of size n, find all elements that appear more than
class Solution {
public:
/*alorithm: hash soluton
1)count elements occurence usin hash table
2)iterate hash table to check whether it > n/3 floor
time O(n) space O(n)
*/
vector<int> majorityElement(vector<int>& nums) {
vector<int>ret;
unordered_map<int,int>hash;
int n = nums.size();
//count
for(int i = 0;i < n;i++){
hash[nums[i]]++;
}
//check n/3 number
for(auto it = hash.begin();it != hash.end();it++){
if(it->second > n/3)
ret.push_back(it->first);
}
return ret;
}
};
⌊ n/3 ⌋times. The algorithm should run in linear time and in O(1) space.
class Solution {
public:
/*alorithm: hash soluton
1)count elements occurence usin hash table
2)iterate hash table to check whether it > n/3 floor
time O(n) space O(n)
*/
vector<int> majorityElement(vector<int>& nums) {
vector<int>ret;
unordered_map<int,int>hash;
int n = nums.size();
//count
for(int i = 0;i < n;i++){
hash[nums[i]]++;
}
//check n/3 number
for(auto it = hash.begin();it != hash.end();it++){
if(it->second > n/3)
ret.push_back(it->first);
}
return ret;
}
};
class Solution { public: /*algorithm:voting algorithm time O(n) space O(1) */ vector<int> majorityElement(vector<int>& nums) { vector<int>ret; int n = nums.size(); int n1,n2,c1,c2; c1 = c2 = 0; for(int i = 0;i < n;i++){ if(n1 == nums[i])c1++; else if(n2 == nums[i])c2++; else if(c1 == 0)n1 = nums[i],c1++; else if(c2 == 0)n2 = nums[i],c2++; else c1--,c2--; } c1 = c2 = 0; for(int i = 0;i < n;i++){ if(n1 == nums[i])c1++; if(n2 == nums[i])c2++; } if(c1 > n/3)ret.push_back(n1); if(c2 > n/3)ret.push_back(n2); return ret; } };
相关文章推荐
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析
- C#获取关键字附近文字算法实例