Skip to content

Commit 7e0ea2c

Browse files
author
weiy
committed
count of smaller numbers after self hard
1 parent 77a49c0 commit 7e0ea2c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Diff for: Array/CountOfSmallerNumbersAfterSelf.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
3+
4+
Example:
5+
6+
Input: [5,2,6,1]
7+
Output: [2,1,1,0]
8+
Explanation:
9+
To the right of 5 there are 2 smaller elements (2 and 1).
10+
To the right of 2 there is only 1 smaller element (1).
11+
To the right of 6 there is 1 smaller element (1).
12+
To the right of 1 there is 0 smaller element.
13+
14+
思路:
15+
二分。
16+
17+
瓶颈依然在于插入列表中的时候需要的时间复杂度为 O(n)。
18+
19+
beat
20+
82%
21+
22+
测试地址:
23+
https://leetcode.com/problems/count-of-smaller-numbers-after-self/description/
24+
25+
"""
26+
import bisect
27+
28+
class Solution(object):
29+
def countSmaller(self, nums):
30+
"""
31+
:type nums: List[int]
32+
:rtype: List[int]
33+
"""
34+
35+
x = []
36+
result = []
37+
38+
for i in nums[::-1]:
39+
result.append(bisect.bisect_left(x, i))
40+
bisect.insort(x,i)
41+
42+
return result[::-1]

0 commit comments

Comments
 (0)