leetcode169 Majority Element-zh
# 169. 多数元素 (opens new window)
English Version (opens new window)
# 题目描述
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:[3,2,3] 输出:3
示例 2:
输入:[2,2,1,1,1,2,2] 输出:2
进阶:
- 尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
# 解法
摩尔投票法。时间复杂度 O(n),空间复杂度 O(1)。
# Python3
class Solution:
def majorityElement(self, nums: List[int]) -> int:
cnt = major = 0
for num in nums:
if cnt == 0:
major = num
cnt = 1
else:
cnt += (1 if major == num else -1)
return major
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# Java
class Solution {
public int majorityElement(int[] nums) {
int cnt = 0, major = 0;
for (int num : nums) {
if (cnt == 0) {
major = num;
cnt = 1;
} else {
cnt += (major == num ? 1 : -1);
}
}
return major;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# JavaScript
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
let cnt = 0;
let major = 0;
for (const num of nums) {
if (cnt == 0) {
major = num;
cnt = 1;
} else {
cnt += (major == num ? 1 : -1);
}
}
return major;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# C++
class Solution {
public:
int majorityElement(vector<int>& nums) {
int cnt = 0, major = 0;
for (int num : nums) {
if (cnt == 0) {
major = num;
cnt = 1;
} else {
cnt += (major == num ? 1 : -1);
}
}
return major;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# C#
public class Solution {
public int MajorityElement(int[] nums) {
int cnt = 0, major = 0;
foreach (int num in nums)
{
if (cnt == 0)
{
major = num;
cnt = 1;
}
else
{
cnt += (major == num ? 1 : -1);
}
}
return major;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38