【leetcode】【easy】剑指 Offer 39. 数组中出现次数超过一半的数字

it2023-09-28  69

 

剑指 Offer 39. 数组中出现次数超过一半的数字

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入: [1, 2, 3, 2, 2, 2, 5, 4, 2] 输出: 2

限制:

1 <= 数组长度 <= 50000

注意:本题与主站 169 题相同:https://leetcode-cn.com/problems/majority-element/

题目链接:

https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/

思路

要点在于:计数为0时,先更新结果变量,再拿当前值与其对比。这样,使得在走到第一个新数的时候,计数能正常为1。

讲的不错的参考题解:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/solution/mo-er-tou-piao-fa-jie-jue-shu-zu-zhong-chu-xian-2/

class Solution { public: int majorityElement(vector<int>& nums) { int len = nums.size(); int cnt = 0, num = -1; for(int i=0; i<len; ++i){ if(cnt==0){ num = nums[i]; } if(nums[i]==num){ ++cnt; }else{ --cnt; } } return num; } };

 

最新回复(0)