Skip to content

Commit 7f52b59

Browse files
authored
Create 1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.md
1 parent c774c2c commit 7f52b59

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
## 1365. How Many Numbers Are Smaller Than the Current Number
2+
3+
Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].
4+
5+
Return the answer in an array.
6+
7+
8+
9+
Example 1:
10+
11+
Input: nums = [8,1,2,2,3]
12+
Output: [4,0,1,1,3]
13+
Explanation:
14+
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
15+
For nums[1]=1 does not exist any smaller number than it.
16+
For nums[2]=2 there exist one smaller number than it (1).
17+
For nums[3]=2 there exist one smaller number than it (1).
18+
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
19+
Example 2:
20+
21+
Input: nums = [6,5,4,8]
22+
Output: [2,1,0,3]
23+
Example 3:
24+
25+
Input: nums = [7,7,7,7]
26+
Output: [0,0,0,0]
27+
28+
29+
Constraints:
30+
31+
2 <= nums.length <= 500
32+
0 <= nums[i] <= 100
33+
34+
35+
```python
36+
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
37+
n = len(nums)
38+
result = [0] * 101
39+
40+
for i in range(n):
41+
result[nums[i]] +=1
42+
43+
for i in range(1, 101):
44+
result[i] += result[i-1]
45+
46+
for i in range(n):
47+
pos = nums[i]
48+
if pos == 0:
49+
nums[i] = 0
50+
else:
51+
nums[i] = result[pos-1]
52+
53+
return nums
54+
```
55+
56+
```
57+
Runtime: 44 ms, faster than 98.58% of Python3 online submissions for How Many Numbers Are Smaller Than the Current Number.
58+
Memory Usage: 14.1 MB, less than 100.00% of Python3 online submissions for How Many Numbers Are Smaller Than the Current Number.
59+
```

0 commit comments

Comments
 (0)