[Leetcode]Majority Element
来源:互联网 发布:c语言windows驱动编程 编辑:程序博客网 时间:2024/06/06 20:08
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.
class Solution {public: /*algorithm1: sort and count the same elememnt time: O(nlogn) space O(1) */ int majorityElement(vector<int>& nums) { if(nums.size() < 1)return 0; int majCnt = 1,cnt = 1; int maj = nums[0]; sort(nums.begin(),nums.end()); for(int i = 1;i < nums.size();i++){ if(nums[i]==nums[i-1]){ cnt++; } if(nums[i] != nums[i-1] || (i+1)==nums.size()){ if(cnt > majCnt){ majCnt = cnt; maj = nums[i-1]; } cnt = 1; } } if(majCnt > nums.size()/2)return maj; return 0; }};class Solution {public: /*algorithm2: count based on hash table time: O(n) space O(n) */ int majorityElement(vector<int>& nums) { unordered_map<int,int>hash; for(int i = 0;i < nums.size();i++)hash[nums[i]]++; for(auto it = hash.begin();it != hash.end();it++){ if(it->second > nums.size()/2)return it->first; } return 0; }}; class Solution {public: /*algorithm3: voting algorithm time: O(n) space O(1) 1,2,2 */ int majorityElement(vector<int>& nums) { int n = nums.size(); if(n < 1)return -1; int maj = nums[0],cnt = 1; for(int i = 1;i < n;i++){ if(maj == nums[i]){ cnt++; }else{ cnt--; if(cnt == 0){ maj = nums[i]; cnt++; } } } cnt = 0; for(int i = 0;i < n;i++){ if(maj == nums[i])cnt++; } if(cnt > n/2)return maj; return -1; }};
0 0
- 【leetcode】Majority Element II,Majority element algorithm
- Leetcode: Majority Element &Majority Element II
- Leetcode Majority Element
- leetcode 169-Majority Element
- 【leetcode 哈希表】Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- leetcode: Majority Element
- [LeetCode] Majority Element
- leetcode 153: Majority Element
- leetcode Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- [LeetCode] Majority Element
- Leetcode-Majority Element
- [leetcode]Majority Element
- [LeetCode]Majority Element
- Leetcode: Majority Element
- gdb 调试常规命令
- android ImageButton的一些使用tip
- 广度优先搜索(BFS)
- spring的6个不同的功能模块
- _cdecl 和_stdcall
- [Leetcode]Majority Element
- Pancake Sorting问题研究与优化
- python正则表达式 分割字符串
- SPFA 求带负权的单源最短路
- HMM的学习笔记1:前向算法
- GDI
- vmware提示:此虚拟机似乎正在使用中,无法取得所有权的解决办法
- 小马哥----高仿三星i8552刷机 详细拆机主板图与开机界面图。2015新主版机 4.12系统
- 排序