mobile wallpaper 1
mobile wallpaper 2
mobile wallpaper 3
mobile wallpaper 4
89 字
1 分钟
LeetCode 面试经典150题 [5/150 多数元素]
2024-06-17
2024-06-18

题目描述#

给定一个大小为 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 * 104
  • -109 <= nums[i] <= 109

个人C++题解#

class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> map;
int count = 0, temp = 0,return_num = 0;
for (auto num : nums) {
count = map[num]++;
if (count >= temp) {
temp = count;
return_num = num;
}
}
return return_num;
}
};
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

LeetCode 面试经典150题 [5/150 多数元素]
https://ericonline.cn/posts/leetcode-面试经典150题-5-150-多数元素/
作者
Eric
发布于
2024-06-17
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录