Skip to content

Commit 5b94b44

Browse files
authored
feat: Updated题目1365,提供了使用数组进行哈希的解法
1 parent 9e02bd0 commit 5b94b44

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

problems/1365.有多少小于当前数字的数字.md

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,9 @@ public int[] smallerNumbersThanCurrent(int[] nums) {
138138

139139
### Python:
140140

141-
```python
141+
> (版本一)使用字典
142+
143+
```python3
142144
class Solution:
143145
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
144146
res = nums[:]
@@ -152,6 +154,23 @@ class Solution:
152154
return res
153155
```
154156
157+
> (版本二)使用数组
158+
159+
```python3
160+
class Solution:
161+
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
162+
# 同步进行排序和创建新数组的操作,这样可以减少一次冗余的数组复制操作,以减少一次O(n) 的复制时间开销
163+
sort_nums = sorted(nums)
164+
# 题意中 0 <= nums[i] <= 100,故range的参数设为101
165+
hash_lst = [0 for _ in range(101)]
166+
# 从后向前遍历,这样hash里存放的就是相同元素最左面的数值和下标了
167+
for i in range(len(sort_nums)-1,-1,-1):
168+
hash_lst[sort_nums[i]] = i
169+
for i in range(len(nums)):
170+
nums[i] = hash_lst[nums[i]]
171+
return nums
172+
```
173+
155174
### Go:
156175

157176
```go

0 commit comments

Comments
 (0)