当前位置:网站首页>【LeetCode】169. 多数元素
【LeetCode】169. 多数元素
2022-08-09 04:55:00 【酥酥~】
题目
给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:nums = [3,2,3]
输出:3
示例 2:
输入:nums = [2,2,1,1,1,2,2]
输出:2
提示:
n == nums.length
1 <= n <= 5 * 104
-109 <= nums[i] <= 109
进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
题解
使用map
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int,int> mymap;
for(int i:nums)
{
mymap[i]++;
if(mymap[i]>nums.size()/2)
return i;
}
return 0;
}
};
排序
因为目标值数量大于n/2,所以排序后下标n/2处一定是目标值
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
return nums[nums.size()/2];
}
};
拼数量
假设打仗时,士兵与敌方士兵1:1互换,则数量大于n/2的一方必然能杀死所有的敌对势力的士兵且有剩余
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 1;
int guard = nums[0];//某方士兵,1个在编
for(int i=1;i<nums.size();i++)
{
if(nums[i] == guard)//遇到我方士兵,数量加一
count++;
else
{
count--;//遇到敌方士兵,数量减一
if(!count)//如果目前已统计的全部死亡,则换一个记录
{
guard = nums[i+1];
}
}
}
return guard;
}
};
边栏推荐
猜你喜欢
数据库设计---三范式和反范式设计
学习笔记_numpy图片基本操作_自用
【Harmony OS】【ARK UI】Date Basic Operation
MySQL: Implementation Principles of Submitted Read and Repeatable Read | MVCC (Multi-Version Concurrency Control) - Notes for Your Own Use
【Harmony OS】【ARK UI】轻量级数据存储
【Harmony OS】【FAQ】鸿蒙问题合集1
Harmony OS ets ArkUI 】 【 】 development create a view and building layout
[MLT] Analysis of MLT Multimedia Framework Production and Consumption Architecture (2)
leetcode:316. 去除重复字母
通讯录(文件版)(C语言)(VS)
随机推荐
ABP中的数据过滤器
供应商对接Chewy的EDI需求
P1163 银行贷款
安装pytorch和cuda
Pycharm Debug调试使用+代码调试理解
力扣202-快乐数——哈希集合
EDI对接 New York & Company案例
杰理之手机OTG问题【篇】
[Harmony OS] [ARK UI] ETS context basic operations
杰理之播放最大音量提示音播不出来【篇】
php使用phpoffice/phpspreadsheet导入导出excel表格
2022 High-altitude installation, maintenance, and demolition exam practice questions and mock exams
Harmony OS ets ArkUI 】 【 】 development create a view and building layout
【暑期每日一题】洛谷 P1176 路径计数2
C进阶-C语言文件操作
【基于富瀚6630使用/dev/fb0显示设备和TDE模块渲染bmp图像】
【Harmony OS】【ARK UI】Lightweight Data Storage
【Harmony OS】【ARK UI】公共事件模块
perl基础语法归纳
如何剪裁svg并压缩