问题
计算右侧小于当前元素的个数
暴力破解
该代码是能输出正确值,但是由于时间复杂度太高,并不能满足上面的范围要求
import numpy as np
class Solution(object):
def countSmaller(self,nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
count=[]
nums = np.array(nums)
for i in range(len(nums)):
x = nums[i];
tmp_num = nums[i:]
count.append(len(tmp_num[tmp_num<x]))
return count
二分查找法
- 该代码Java能过,但是python不能过
class Solution {
//binary search - returns first index of num in list
private int bSearch(List<Integer> list, int num){
int start = 0;
int end = list.size()-1;
while(start < end){
int middle = (end-start)/2 + start;
if(list.get(middle) < num) {
start = middle+1;
} else {
end = middle;
}
}
return start;
}
public List<Integer> countSmaller(int[] nums) {
List<Integer> list = new ArrayList<>(); //result list
if(nums.length == 0)
return list;
//copy all numbers to list
List<Integer> copy = new ArrayList<>();
for(int num : nums){
copy.add(num);
}
//sort the list (nlogn)
Collections.sort(copy);
for(int num : nums){
//find first index in sorted array (logn)
int index = bSearch(copy, num);
//add to result
list.add(index);
//remove for next iteration
copy.remove(index);
}
return list;
}
}
使用Python标准库 sortedcontainers.sortedlist
from sortedcontainers import SortedList
class Solution:
def countSmaller(self,nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
count=[0]*len(nums)
sortedlists = SortedList()
for i in range(len(nums)-1,-1,-1):
##二分查找,返回左侧位置
co = sortedlists.bisect_left(nums[i])
sortedlists.add(nums[i])
count[i]=co
return count
使用树状数组,求取逆序对
import numpy as np
class Solution:
def update(self,bitTree,x):
i = x
while(i<=len(bitTree)-1):
bitTree[i]+=1
i =i+ (i&(-i))
return bitTree
def getSum(self,bitTree,x):
con_sum =0
i = x
while(i>0):
con_sum=con_sum+bitTree[i]
i -= (i&(-i))
return con_sum
def countSmaller(self,nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
num_arr = np.array(nums)
num_arr = num_arr-np.min(num_arr)+1
num_max = np.max(num_arr)
bitTree = [0]*(num_max+1)
count = [0]*(len(nums))
# print(bitTree)
for i in range(len(num_arr)-1,-1,-1):
##num_arr[i]-1:表示只求取小于num_arr[i]-1 的所有数字和
count[i] = Solution.getSum(self,bitTree,num_arr[i]-1)
print(count[i])
bitTree= Solution.update(self,bitTree,num_arr[i])
return count