BM51. 数组中出现次数超过一半的数字
描述
输入描述
保证数组输入非空,且保证有解示例1
输入:
[1,2,3,2,2,2,5,4,2]
输出:
2
示例2
输入:
[3,3,3,3,2,2,2]
输出:
3
示例3
输入:
[1]
输出:
1
C++ 解法, 执行用时: 3ms, 内存消耗: 1068KB, 提交时间: 2021-09-12
static const auto io_sync_off =[](){ std::ios::sync_with_stdio(false); cin.tie(nullptr); return nullptr; }(); class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { int len=numbers.size(); map<int,int> m; int res=0; for(int i=0;i<len;i++) { m[numbers[i]]++; if(m[numbers[i]]>len/2) { res=numbers[i]; break; } } return res; } };
C++ 解法, 执行用时: 4ms, 内存消耗: 904KB, 提交时间: 2021-09-13
class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { sort(numbers.begin(),numbers.end()); int tmp = numbers[numbers.size()/2]; int num = 0; for(int i = 0 ; i < numbers.size(); i++) { if(tmp == numbers[i]) { num++; } } if (num > numbers.size()/2) return tmp; else return 0; } };
C++ 解法, 执行用时: 4ms, 内存消耗: 908KB, 提交时间: 2021-09-10
class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { int count = 0; int res = numbers[0]; for(int i = 0;i < numbers.size();i++) { if(numbers[i] == res) { count++; } else { count--; if(count < 0) { res = numbers[i]; count = 1; } } } return res; } };
C++ 解法, 执行用时: 4ms, 内存消耗: 908KB, 提交时间: 2021-09-08
class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { int count=0; int candidate=0; for(auto i:numbers){ if(count==0){ candidate=i; count++; } else{ if(i==candidate)count++; else count--; } } return candidate; } };
C++ 解法, 执行用时: 4ms, 内存消耗: 912KB, 提交时间: 2021-09-09
class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { unordered_map<int, int> mp; for(int i=0; i<numbers.size(); ++i){ ++mp[numbers[i]]; } for(int i=0; i<numbers.size(); ++i){ if(mp[numbers[i]] > numbers.size()/2){ return numbers[i]; } } return 0; } };