当前位置:网站首页>leetcode-169.多数元素
leetcode-169.多数元素
2022-07-26 03:14:00 【KGundam】
数学问题
题目详情
给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例1:
输入:nums = [3,2,3]
输出:3
示例2:
输入:nums = [2,2,1,1,1,2,2]
输出:2
思路:
题目中一个重要的点是给定的数组一定存在多数元素,即在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素
那么这道题就可以用摩尔投票法解决了,摩尔投票法就是遍历数组,先将第一个数设置为"候选人" candidate,然后将票数cnt’初始化为1(只有他自己的一票),然后往后面遍历,如果遇到相同数,就加票,不同数则减票,如果票数减到0了,就更换下一个候选人,继续遍历(注意后面的候选人可能会和前面候选人重复,所以不必回头遍历)
再借用评论区一位大神对摩尔投票法的形象描述:
摩尔投票法:
核心就是对拼消耗。
玩一个诸侯争霸的游戏,假设你方人口超过总人口一半以上,并且能保证每个人口出去干仗都能一对一同归于尽。最后还有人活下来的国家就是胜利。
那就大混战呗,最差所有人都联合起来对付你(对应你每次选择作为计数器的数都是众数),或者其他国家也会相互攻击(会选择其他数作为计数器的数),但是只要你们不要内斗,最后肯定你赢。
最后能剩下的必定是自己人.
我的代码:
class Solution
{
public:
int majorityElement(vector<int>& nums)
{
int n = nums.size(), candidate = nums[0], cnt = 1;
//因为初始化candidate为nums[0]所以i要从1开始遍历了
for (int i = 1; i < n; ++i)
{
if (candidate == nums[i]) //如果遇到相同的数
{
++cnt; //就"加一票"
}
else //遇到不同的数
{
--cnt; //就"减一票"
if (cnt == 0) //减完票如果没票了
{
//说明这个候选人的票绝对不是大于n/2的(即不为多数元素)
candidate = nums[i]; //那就更换下一个候选人
cnt = 1; //初始票再次为1
}
}
}
return candidate;
}
};
边栏推荐
猜你喜欢

snownlp库各功能及用法

ext4、ntfs、xfs、btrfs、zfs、f2fs和reiserFS性能对比

经典面试问题——OOP语言的三大特征

Course notes of single chip microcomputer principle and interface technology for migrant workers majoring in electronic information engineering

Classic interview questions -- three characteristics of OOP language
![[Yuri crack man] brings you easy understanding - deep copy and shallow copy](/img/26/b7330c7f5fdac55c8f5e9fa24658ee.png)
[Yuri crack man] brings you easy understanding - deep copy and shallow copy

Hcip day 8 notes sorting (OSPF routing control, Appendix E, anti ring, shortest path calculation, republication))

线性回归原理推导

【创建交互式 Dice Roller 应用】

图解LeetCode——5. 最长回文子串(难度:中等)
随机推荐
Type the URL to the web page display. What happened during this period?
Canvas - drawing pictures - dynamic drawing production
Digital commerce cloud DMS dealer management system solution: DMS system realizes business Omni channel and sales data collection
canvas——矩形的绘制——柱状图的制作
2020 AF-RCNN: An anchor-free convolutional neural network for multi-categoriesagricultural pest det
Use eventlog analyzer for log forensics analysis
了解预加载和懒加载、学会缓动动画
UDP和TCP可以使用同一个端口吗?
Opencv error: (parameter or structure field)) unrecognized or unsupported array type in functon 'cvgetmat‘
els 初始化窗口类
使用anaconda配置gpu版本的tensorflow(30系列以下显卡)
堆内存与栈内存的区别?
实现一个方法,找出数组中的第k大和第m大的数字相加之和
What are you interviewing for in a big factory? It's worth watching (I)
TCP experimental verification
【数学建模-规划模型总结】| MATLAB求解
Derivation of linear regression principle
Service gateway (zuul)
Unknown-Aware Object Detection:Learning What You Don’t Know from Videos in the Wild(CVPR 2022)
Illustration leetcode - 5. Longest palindrome substring (difficulty: medium)