-
Notifications
You must be signed in to change notification settings - Fork 420
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
count of smaller numbers after self hard
- Loading branch information
weiy
committed
Nov 1, 2018
1 parent
77a49c0
commit 7e0ea2c
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
""" | ||
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]. | ||
Example: | ||
Input: [5,2,6,1] | ||
Output: [2,1,1,0] | ||
Explanation: | ||
To the right of 5 there are 2 smaller elements (2 and 1). | ||
To the right of 2 there is only 1 smaller element (1). | ||
To the right of 6 there is 1 smaller element (1). | ||
To the right of 1 there is 0 smaller element. | ||
思路: | ||
二分。 | ||
瓶颈依然在于插入列表中的时候需要的时间复杂度为 O(n)。 | ||
beat | ||
82% | ||
测试地址: | ||
https://leetcode.com/problems/count-of-smaller-numbers-after-self/description/ | ||
""" | ||
import bisect | ||
|
||
class Solution(object): | ||
def countSmaller(self, nums): | ||
""" | ||
:type nums: List[int] | ||
:rtype: List[int] | ||
""" | ||
|
||
x = [] | ||
result = [] | ||
|
||
for i in nums[::-1]: | ||
result.append(bisect.bisect_left(x, i)) | ||
bisect.insort(x,i) | ||
|
||
return result[::-1] |