-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path169.多数元素.py
69 lines (64 loc) · 1.28 KB
/
169.多数元素.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#
# @lc app=leetcode.cn id=169 lang=python3
#
# [169] 多数元素
#
# https://leetcode.cn/problems/majority-element/description/
#
# algorithms
# Easy (66.40%)
# Likes: 2062
# Dislikes: 0
# Total Accepted: 817.8K
# Total Submissions: 1.2M
# Testcase Example: '[3,2,3]'
#
# 给定一个大小为 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) 的算法解决此问题。
#
#
# @lc code=start
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
"""使用 dict, 空间复杂度最差情况为 O(n)"""
d = dict()
max_count = 0
item = None
for i in nums:
count = d.get(i, 0) + 1
if count > max_count:
max_count = count
item = i
d[i] = count
return item
# @lc code=end