剑指 Offer 39. 数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000
注意:本题与主站 169 题相同:https://leetcode-cn.com/problems/majority-element/
来源:力扣(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的元素认为自己是出现次数超过一半的元素;
最后返回一个最大值。
投票法代码:
class Solution: def majorityElement(self, nums: List[int]) -> int: votes = 0 for num in nums: if votes == 0: majorityElement = num if num == majorityElement: votes += 1 else: votes -= 1 return majorityElement
写python的大佬总想用语法糖玩一点花的:(其实性能也没有快多少)
class Solution: def majorityElement(self, nums: List[int]) -> int: votes = 0 for num in nums: if votes == 0: majorityElement = num votes += 1 if num == majorityElement else -1 return majorityElement
此外,题目中总是假设存在一个超过半数的元素的,但是如果没有呢...这个算法得到一个出现次数最多的元素,但是不一定是超过半数的,所以大佬需要进行判断,检验得到的数是否为众数
class Solution: def majorityElement(self, nums: List[int]) -> int: votes, count = 0, 0 for num in nums: if votes == 0: majorityElement = num votes += 1 if num == majorityElement else -1 for num in nums: if num == majorityElement: count += 1 return majorityElement if count > len(nums) // 2 else 0
时间复杂度:O(n)
空间复杂度:O(1)
解法2:
字典法:
遍历整个列表,并在hash表中存储为数字-出现的次数(键值对)对的形式,最后返回出现次数最多的元素
对于重复元素,本人永远只会用集合的方式初始化字典,字典的初始化还有别的方式嘛?
class Solution: def majorityElement(self, nums: List[int]) -> int: dic = {} numbers = set(nums) for item in numbers: dic[item] = 0 for item in nums: dic[item] += 1 res = 0 for k, v in dic.items(): if v > len(nums) // 2: res = k return res
时间复杂度:O(n),最多只遍历了一遍列表
空间复杂度:O(n),需要额外的空间存放元素
解法三:
排序法:
思想:排序之后,列表中点的元素一定是超过半数的元素
排序法:
class Solution: def majorityElement(self, nums: List[int]) -> int: return sorted(nums)[len(nums) // 2]
人生苦短!我用Python!
时间复杂度:O(nlogn),因为限制比较少的最快的排序算法,复杂度就O(nlogn)
空间复杂度:???