数组中出现次数超过一半的数字(Python and C++解法)

题目:

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof

思路:

  如果数组中一个数字出现的次数超过了数组长度一半,那么它出现的次数比其他所有数字出现的次数,之和还要多,因此可以进行投票,正负相抵,假设众数票额为+1,其他票额为-1,那么最终票数之和>0,如果当前票数之和为0,那么设当前数字为众数,则最后一次假设的众数一定是真众数。

Python解法:

 1 class Solution:
 2     def majorityElement(self, nums: List[int]) -> int:
 3         votes = 0  # 投票总和,假设众数票额为+1,其他为-1
 4         for num in nums:
 5             if votes == 0:  # 如果当前票数和为零,则假设当前的数字为众数
 6                 x = num
 7             if num == x:
 8                 votes += 1
 9             else:
10                 votes -= 1
11         return x

C++解法:

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         int votes = 0;
 5         int x;  // 假设的众数
 6         for(int i = 0; i < nums.size(); i++) {
 7             if(votes == 0)
 8                 x = nums[i];
 9             if(nums[i] == x)
10                 votes += 1;
11             else
12                 votes -= 1;
13         }
14         return x;
15     }
16 };
原文地址:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13300314.html