当前位置:网站首页>【剑指offer】面试题39:数组中出现次数超过一半的数字
【剑指offer】面试题39:数组中出现次数超过一半的数字
2022-07-27 14:24:00 【Jocelin47】
方法二:通过索引记录——摩尔投票法
通过记录一个次数times,
如果当前数字和下一个数字结果不相等,则times–
如果相同则times++
最后的保存的结果就是超过一半的数
class Solution {
public:
int majorityElement(vector<int>& nums) {
if( nums.size() == 0 )
return 0;
int result = nums[0];
int times = 1;
for( int i = 1; i < nums.size(); i++)
{
if( nums[i] == result )
times++;
else if( times == 0)
result = nums[i];
else
times--;
}
return result;
}
};
方法三:哈希表查找
class Solution {
public:
int majorityElement(vector<int>& nums) {
if( nums.size() == 0 )
return 0;
unordered_map<int,int> record;
for( auto num : nums)
{
record[num]++;
if( record[num] > (nums.size() / 2) )
return num;
}
return 0;
}
};
边栏推荐
- Unity性能优化------DrawCall
- Singles cup, web:web check in
- Inside router of network equipment hard core technology (10) disassembly of Cisco asr9900 (4)
- AssetBundle如何打包
- 适配验证新职业来了!华云数据参与国家《信息系统适配验证师国家职业技能标准》编制
- QT (IV) mixed development using code and UI files
- Some binary bit operations
- Watermelon book machine learning reading notes Chapter 1 Introduction
- Overview of wechat public platform development
- Sword finger offer merges two sorted linked lists
猜你喜欢

Four kinds of relay schemes driven by single chip microcomputer

JUC(JMM、Volatile)

复杂度分析
![[0 basic operations research] [super detail] column generation](/img/cd/f2521824c9ef6a50ec2be307c584ca.png)
[0 basic operations research] [super detail] column generation

Leetcode 190. reverse binary bit operation /easy
USB interface electromagnetic compatibility (EMC) solution

Google team launches new transformer to optimize panoramic segmentation scheme CVPR 2022

MySQL interview 40 consecutive questions, interviewer, if you continue to ask, I will turn my face

reflex

Spark 3.0 Adaptive Execution 代码实现及数据倾斜优化
随机推荐
How to edit a framework resource file separately
Leetcode 456.132 mode monotone stack /medium
扩展Log4j支持日志文件根据时间分割文件和过期文件自动删除功能
Design scheme of digital oscilloscope based on stm32
[daily question 1] 558. Intersection of quadtrees
【剑指offer】面试题55 - Ⅰ/Ⅱ:二叉树的深度/平衡二叉树
Is it safe to open an account on a mobile phone?
Network equipment hard core technology insider router Chapter 17 dpdk and its prequel (II)
【剑指offer】面试题53-Ⅰ:在排序数组中查找数字1 —— 二分查找的三个模版
设置提示框位置随鼠标移动,并解决提示框显示不全的问题
Spark 本地程序启动缓慢问题排查
《终身成长》读书笔记(一)
HJ8 合并表记录
复杂度分析
Leetcode 783. binary search tree node minimum distance tree /easy
Unity performance optimization ----- occlusion culling of rendering optimization (GPU)
Spark 3.0 DPP实现逻辑
AssetBundle如何打包
Network equipment hard core technology insider router Chapter 14 from deer by device to router (middle)
Pytorch replaces some components in numpy. / / please indicate the source of the reprint