mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
feat: Updated题目1365,提供了使用数组进行哈希的解法
This commit is contained in:
@ -138,7 +138,9 @@ public int[] smallerNumbersThanCurrent(int[] nums) {
|
||||
|
||||
### Python:
|
||||
|
||||
```python
|
||||
> (版本一)使用字典
|
||||
|
||||
```python3
|
||||
class Solution:
|
||||
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
|
||||
res = nums[:]
|
||||
@ -152,6 +154,23 @@ class Solution:
|
||||
return res
|
||||
```
|
||||
|
||||
> (版本二)使用数组
|
||||
|
||||
```python3
|
||||
class Solution:
|
||||
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
|
||||
# 同步进行排序和创建新数组的操作,这样可以减少一次冗余的数组复制操作,以减少一次O(n) 的复制时间开销
|
||||
sort_nums = sorted(nums)
|
||||
# 题意中 0 <= nums[i] <= 100,故range的参数设为101
|
||||
hash_lst = [0 for _ in range(101)]
|
||||
# 从后向前遍历,这样hash里存放的就是相同元素最左面的数值和下标了
|
||||
for i in range(len(sort_nums)-1,-1,-1):
|
||||
hash_lst[sort_nums[i]] = i
|
||||
for i in range(len(nums)):
|
||||
nums[i] = hash_lst[nums[i]]
|
||||
return nums
|
||||
```
|
||||
|
||||
### Go:
|
||||
|
||||
```go
|
||||
|
Reference in New Issue
Block a user