当前位置:网站首页>面试题 17.10. 主要元素
面试题 17.10. 主要元素
2022-06-11 09:06:00 【Mr Gao】
面试题 17.10. 主要元素
数组中占比超过一半的元素称之为主要元素。给你一个 整数 数组,找出其中的主要元素。若没有,返回 -1 。请设计时间复杂度为 O(N) 、空间复杂度为 O(1) 的解决方案。
示例 1:
输入:[1,2,5,9,5,9,5,5,5]
输出:5
示例 2:
输入:[3,2]
输出:-1
示例 3:
输入:[2,2,1,1,1,2,2]
输出:2
这一题没什么特别难的地方,我们需要利用一下,这题数据分布的情况
解题代码如下:
int majorityElement(int* nums, int numsSize){
int count=1;
int x=nums[0];
int i;
for(i=1;i<numsSize;i++){
if(count==0){
x=nums[i];
count++;
continue;
}
if(nums[i]==x){
count++;
}
else{
count--;
}
}
count=0;
for(i=0;i<numsSize;i++){
if(nums[i]==x){
count++;
}
}
if(count>numsSize/2){
return x;
}
else{
return -1;
}
}
边栏推荐
- openstack详解(二十三)——Neutron其他配置、数据库初始化与服务启动
- 移动端页面使用rem来做适配
- PVC plastic sheets BS 476-6 determination of flame propagation properties
- Matlab learning 8- linear and nonlinear sharpening filtering and nonlinear smoothing filtering of image processing
- Pytorch installation for getting started with deep learning
- TextView文本大小自动适配与TextView边距的去除
- 【C语言-数据存储】数据在内存中是怎样存储的?
- E. Zoom in and zoom out of X (operator overloading)
- Android 面试笔录(精心整理篇)
- LiveData 与 StateFlow,我该用哪个?
猜你喜欢

M1 chip guide: M1, M1 pro, M1 Max and M1 ultra

矩阵求逆操作的复杂度分析(逆矩阵的复杂度分析)

File system check of the root filesystem failed

typescript高阶特性一 —— 合并类型(&)

Android 面试笔录(精心整理篇)

Exclusive interview with PMC member Liu Yu: female leadership in Apache pulsar community

Award winning survey streamnational sponsored 2022 Apache pulsar user questionnaire

Iso8191 test is mentioned in as 3744.1. Are the two tests the same?

机器学习笔记 - 使用TensorFlow的Spatial Transformer网络

What software is required to process raw format images?
随机推荐
Are the test methods of CMVSS TSD No. 302 and 49 CFR 571.302 the same
Install jupyter in the specified environment
Matlab learning 8- linear and nonlinear sharpening filtering and nonlinear smoothing filtering of image processing
矩阵求逆操作的复杂度分析(逆矩阵的复杂度分析)
Livedata and stateflow, which should I use?
typescript高阶特性一 —— 合并类型(&)
C language printing diamond
PCBA方案定制,开发腕式血压计方案
2095. delete the intermediate node of the linked list
企业决议时,哪个部分应该主导ERP项目?
openstack详解(二十一)——Neutron组件安装与配置
MSF evasion模块的使用
Pytorch installation for getting started with deep learning
How to apply for BS 476-7 sample for display? Is it the same as the display
ERP体系能帮忙企业处理哪些难题?
[image processing] spatial domain image enhancement
SAP OData development tutorial
leveldb简单使用样例
multiplication table
2130. maximum twin sum of linked list