feat: Update 1365,添加python的暴力法,并将哈希法的两种方法合并写在一起

This commit is contained in:
Yuan Yuan
2024-12-04 12:43:06 -06:00
committed by GitHub
parent e1034946d5
commit 66caa02935

View File

@ -138,10 +138,28 @@ public int[] smallerNumbersThanCurrent(int[] nums) {
### Python ### Python
> (版本一)使用字典 > 暴力法
```python3 ```python3
class Solution: class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
res = [0 for _ in range(len(nums))]
for i in range(len(nums)):
cnt = 0
for j in range(len(nums)):
if j == i:
continue
if nums[i] > nums[j]:
cnt += 1
res[i] = cnt
return res
```
> 排序+hash
```python3
class Solution:
# 方法一:使用字典
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
res = nums[:] res = nums[:]
hash_dict = dict() hash_dict = dict()
@ -152,12 +170,8 @@ class Solution:
for i, num in enumerate(nums): for i, num in enumerate(nums):
res[i] = hash_dict[num] res[i] = hash_dict[num]
return res return res
```
> (版本二)使用数组 # 方法二:使用数组
```python3
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
# 同步进行排序和创建新数组的操作这样可以减少一次冗余的数组复制操作以减少一次O(n) 的复制时间开销 # 同步进行排序和创建新数组的操作这样可以减少一次冗余的数组复制操作以减少一次O(n) 的复制时间开销
sort_nums = sorted(nums) sort_nums = sorted(nums)