力扣链接:169. 多数元素,难度等级:简单。
给定一个大小为 n
的数组 nums
,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: nums = [3,2,3]
输出: 3
示例 2:
输入: nums = [2,2,1,1,1,2,2]
输出: 2
约束:
n == nums.length
1 <= n <= 5 * 10^4
-10^9 <= nums[i] <= 10^9
进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
提示 1
How to solve the problem in O(1)
space?
Please search Boyer-Moore majority vote algorithm
.
复杂度
时间复杂度
O(N)
空间复杂度
O(N)
Python #
class Solution:
def majorityElement(self, nums: List[int]) -> int:
num_to_count = defaultdict(int)
for num in nums:
num_to_count[num] += 1
if num_to_count[num] >= len(nums) / 2:
return num
Ruby #
# @param {Integer[]} nums
# @return {Integer}
def majority_element(nums)
num_to_count = Hash.new(0)
nums.each do |num|
num_to_count[num] += 1
if num_to_count[num] > nums.size / 2
return num
end
end
end
Java #
class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> numToCount = new HashMap<>();
for (int num : nums) {
numToCount.put(num, numToCount.getOrDefault(num, 0) + 1);
if (numToCount.get(num) > nums.length / 2) {
return num;
}
}
return -1; // This line won't be reached due to problem constraints
}
}