Skip to content

Commit 732461e

Browse files
authored
Update 222
+ 修正了原始的错误 + 添加了其他 3 种方法
1 parent 7783a8f commit 732461e

File tree

1 file changed

+41
-3
lines changed

1 file changed

+41
-3
lines changed

README.md

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2447,11 +2447,49 @@ redis检查内存使用情况,如果大于maxmemory的限制,则根据设定
24472447

24482448
## 数据结构
24492449
### 222.数组中出现次数超过一半的数字-Python版
2450-
```pythondef
2451-
def majorityElement(nums):
2450+
2451+
#### 方法一
2452+
2453+
```python
2454+
def majority_element(nums):
24522455
nums.sort()
2453-
return nums[len(nums)/2]
2456+
return nums[len(nums) // 2]
24542457
```
2458+
2459+
#### 方法二
2460+
2461+
```python
2462+
from functools import reduce
2463+
2464+
2465+
def majority_element(nums):
2466+
return reduce(lambda n, x: (n[0], n[1] + 1) if n == x else ((x, 1) if n[1] - 1 < 0 else (n[0], n[1] - 1)), nums, (None, -1))[0]
2467+
```
2468+
2469+
#### 方法三
2470+
2471+
```python
2472+
from collections import Counter
2473+
2474+
2475+
def majority_element(nums):
2476+
return Counter(nums).most_common(1)[0][0]
2477+
```
2478+
2479+
#### 方法四
2480+
2481+
```python
2482+
from random import choice
2483+
2484+
2485+
def majority_element(nums):
2486+
length = len(nums) // 2
2487+
while True:
2488+
n = choice(nums)
2489+
if nums.count(n) > length:
2490+
return n
2491+
```
2492+
24552493
### 223.求100以内的质数
24562494
### 224.无重复字符的最长子串-Python实现
24572495
### 225.通过2个5/6升得水壶从池塘得到3升水

0 commit comments

Comments
 (0)