当前位置:网站首页>[sword finger offer] interview question 39: numbers that appear more than half of the time in the array
[sword finger offer] interview question 39: numbers that appear more than half of the time in the array
2022-07-27 15:51:00 【Jocelin47】
Method 2 : Record by index —— Moore voting
By recording a number times,
If the result of the current number and the next number are not equal , be times–
If it's the same times++
The last saved result is more than half of the number
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;
}
};
Method 3 : Hash table lookup
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;
}
};
边栏推荐
- HaoChen CAD building 2022 software installation package download and installation tutorial
- C语言:字符串函数与内存函数
- C语言:扫雷小游戏
- C language: Sanzi game
- 【剑指offer】面试题45:把数组排成最小的数
- Go language slow start - Basic built-in types
- 复杂度分析
- On juicefs
- Spark Bucket Table Join
- Database: use the where statement to retrieve (header song)
猜你喜欢

线程中死锁的成因及解决方案

Alibaba's latest summary 2022 big factory interview real questions + comprehensive coverage of core knowledge points + detailed answers

网络层的IP协议

数组名是首元素地址吗?

后台返回来的是这种数据,是什么格式啊

【剑指offer】面试题49:丑数

Binder initialization process

Binary Insertion Sort

线程间等待与唤醒机制、单例模式、阻塞队列、定时器

QT (IV) mixed development using code and UI files
随机推荐
MLX90640 红外热成像仪测温传感器模块开发笔记(七)
$router.back(-1)
[正则表达式] 匹配分组
网络设备硬核技术内幕 路由器篇 小结(下)
[regular expression] single character matching
Insert sort directly
【剑指offer】面试题55 - Ⅰ/Ⅱ:二叉树的深度/平衡二叉树
QT (five) meta object properties
使用Lombok导致打印的tostring中缺少父类的属性
Network principle (2) -- network development
Explanation of various attributes of "router link"
【剑指offer】面试题50:第一个只出现一次的字符——哈希表查找
[系统编程] 进程,线程问题总结
Three uses of static keyword
Network principle (1) - overview of basic principles
Analysis of spark task scheduling exceptions
NPM install error unable to access
线程中死锁的成因及解决方案
Troubleshooting the slow startup of spark local programs
leetcode-1:两数之和