【力扣-多数元素 JAVA/Python】
题目描述
解题思路:
数组中出现次数超过一半的数字
有两种解法:
1、把数组排序,中位数一定是众数
2、Boyer-Moore 投票算法: 票数正负抵消,时间O(N) 空间复杂度O(1) 所以用这个解法最合适。
🔍 举例
数组:[2,2,1,1,1,2,2]
初始:candidate=2, count=1
遍历:
-
遇到 2 → 相同 → count=2
-
遇到 1 → 不同 → count=1
-
遇到 1 → 不同 → count=0 → 换候选人 = 1, count=1
-
遇到 1 → 相同 → count=2
-
遇到 2 → 不同 → count=1
-
遇到 2 → 不同 → count=0 → 换候选人 = 2, count=1
-
最后 candidate=2,它就是多数元素 ✅
流程图如下:
代码如下:
python版本
class Solution(object):def majorityElement(self, nums):""":type nums: List[int]:rtype: int"""count = 0person = Nonefor i in range(len(nums)):if count == 0:person = nums[i]count = 1elif person == nums[i]:count += 1else:count -= 1return person
java版本
class Solution {public int majorityElement(int[] nums) {int count = 1, person = nums[0];for(int i = 1; i < nums.length ; i ++){if(count == 0){person = nums[i];count = 1;}else if(nums[i] == person){count++;}else{count--;}}return person;}
}