当前位置:网站首页>【剑指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;
}
};
边栏推荐
- Network equipment hard core technology insider router Chapter 6 tompkinson roaming the online world (middle)
- Leetcode 240. search two-dimensional matrix II medium
- 【剑指offer】面试题56-Ⅰ:数组中数字出现的次数Ⅰ
- Discussion on STM32 power down reset PDR
- 谷粒商城配置CorsWebFilter后,报错:Resource sharing error:MultipleAllowOriginValues
- js使用一元运算符简化字符串转数字
- Reading notes of lifelong growth (I)
- /dev/loop1占用100%问题
- EMC design scheme of USB2.0 Interface
- Spark 3.0 测试与使用
猜你喜欢

Method of removing top navigation bar in Huawei Hongmeng simulator

Four kinds of relay schemes driven by single chip microcomputer

Leetcode 240. search two-dimensional matrix II medium

华云数据打造完善的信创人才培养体系 助力信创产业高质量发展

EMC design scheme of USB2.0 Interface

STM32 can communication filter setting problem

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

Spark 3.0 Adaptive Execution 代码实现及数据倾斜优化

Basic usage of kotlin

3.3-5v转换
随机推荐
js使用for in和for of来简化普通for循环
Spark3中Catalog组件设计和自定义扩展Catalog实现
Leetcode-1737- minimum number of characters to change if one of the three conditions is met
/dev/loop1占用100%问题
lua学习笔记
Unity performance optimization ----- LOD (level of detail) of rendering optimization (GPU)
EMC design scheme of RS485 interface
TCC
STM32 can communication filter setting problem
Transactions_ Basic demonstrations and transactions_ Default auto submit & manual submit
设置提示框位置随鼠标移动,并解决提示框显示不全的问题
$router.back(-1)
[0 basic operations research] [super detail] column generation
魔塔项目中的问题解决
Sword finger offer merges two sorted linked lists
使用双星号代替Math.pow()
HaoChen CAD building 2022 software installation package download and installation tutorial
Network equipment hard core technology insider router Chapter 13 from deer by device to router (Part 1)
【剑指offer】面试题56-Ⅰ:数组中数字出现的次数Ⅰ
Pytorch replaces some components in numpy. / / please indicate the source of the reprint