返回
LeetCode数据结构基础:用好字典,轻松找到“多数元素”!
前端
2023-10-05 19:19:30
多数元素
多数元素是指在一个非空数组中,出现次数超过数组长度一半的元素。寻找多数元素是LeetCode数据结构基础中的一个经典问题,也是面试中的常考题。
算法概述
要找出多数元素,我们可以采用一种称为“字典计数”的算法。具体步骤如下:
- 创建一个字典,用于存储数组中出现的元素及其对应的出现次数。
- 遍历数组,对于每个元素,在字典中查找该元素是否已经存在。
- 如果存在,则将其出现次数加1。
- 如果不存在,则将该元素添加到字典中,并将其出现次数设为1。
- 在字典中找到出现次数超过数组长度一半的元素,并将其返回。
代码实现
Python
def majority_element(nums):
"""
:type nums: List[int]
:rtype: int
"""
# 创建字典存储元素及其出现次数
counts = {}
for num in nums:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
# 寻找出现次数超过数组长度一半的元素
majority = None
for num, count in counts.items():
if count > len(nums) / 2:
majority = num
break
return majority
Java
import java.util.HashMap;
class Solution {
/**
* Finds the majority element in a given array.
*
* @param nums The input array.
* @return The majority element.
*/
public int majorityElement(int[] nums) {
// Create a HashMap to store the elements and their counts.
HashMap<Integer, Integer> counts = new HashMap<>();
// Iterate over the array and update the counts.
for (int num : nums) {
if (counts.containsKey(num)) {
counts.put(num, counts.get(num) + 1);
} else {
counts.put(num, 1);
}
}
// Find the element with the highest count.
int majority = 0;
int maxCount = 0;
for (int num : counts.keySet()) {
int count = counts.get(num);
if (count > maxCount) {
majority = num;
maxCount = count;
}
}
return majority;
}
}
复杂度分析
- 时间复杂度:算法的时间复杂度为O(n),其中n为数组的长度。这是因为我们只需要遍历数组一次,并且在字典中查找元素的时间复杂度为O(1)。
- 空间复杂度:算法的空间复杂度为O(n),这是因为我们使用字典来存储元素及其出现次数。
结语
通过今天的分享,我们一起探索了LeetCode数据结构基础系列中的“多数元素”这一经典算法。我们使用了Python和Java两种语言,详细讲解了如何运用字典数据结构高效地解决此问题,助您轻松掌握算法精髓!