Skip to content

Commit c50f10e

Browse files
committed
feat: add python and java solutions to lcof problem
添加《剑指 Offer》题解:面试题39. 数组中出现次数超过一半的数字
1 parent 164ddad commit c50f10e

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# [面试题39. 数组中出现次数超过一半的数字](https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/)
2+
3+
## 题目描述
4+
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
5+
6+
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
7+
8+
**示例 1:**
9+
10+
```
11+
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
12+
输出: 2
13+
```
14+
15+
**限制:**
16+
17+
- `1 <= 数组长度 <= 50000`
18+
19+
## 解法
20+
摩尔投票法。时间复杂度 O(n),空间复杂度 O(1)。
21+
22+
### Python3
23+
```python
24+
class Solution:
25+
def majorityElement(self, nums: List[int]) -> int:
26+
cnt = major = 0
27+
for num in nums:
28+
if cnt == 0:
29+
major = num
30+
cnt += 1
31+
else:
32+
cnt += (1 if major == num else -1)
33+
return major
34+
```
35+
36+
### Java
37+
```java
38+
class Solution {
39+
public int majorityElement(int[] nums) {
40+
int major = 0, cnt = 0;
41+
for (int num : nums) {
42+
if (cnt == 0) {
43+
major = num;
44+
++cnt;
45+
} else {
46+
cnt += (num == major ? 1 : -1);
47+
}
48+
}
49+
return major;
50+
}
51+
}
52+
```
53+
54+
### ...
55+
```
56+
57+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution {
2+
public int majorityElement(int[] nums) {
3+
int major = 0, cnt = 0;
4+
for (int num : nums) {
5+
if (cnt == 0) {
6+
major = num;
7+
++cnt;
8+
} else {
9+
cnt += (num == major ? 1 : -1);
10+
}
11+
}
12+
return major;
13+
}
14+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class Solution:
2+
def majorityElement(self, nums: List[int]) -> int:
3+
cnt = major = 0
4+
for num in nums:
5+
if cnt == 0:
6+
major = num
7+
cnt += 1
8+
else:
9+
cnt += (1 if major == num else -1)
10+
return major

0 commit comments

Comments
 (0)