1. 解题思路
这一题不太明白为啥被划分为了hard的题目,我们只需要按照题意构造一下arr1
和arr2
即可,唯一的难点就在于greaterCount(arr, val)
函数的实现,不过我们也只需要另外在构造一组有序的arr1
和arr2
即可快速得到其结果了。
2. 代码实现
给出python代码实现如下:
class Solution:
def resultArray(self, nums: List[int]) -> List[int]:
arr1 = [nums[0]]
arr2 = [nums[1]]
sorted_arr1 = [nums[0]]
sorted_arr2 = [nums[1]]
def greater_count(arr, val):
idx = bisect.bisect_right(arr, val)
return len(arr)-idx
for x in nums[2:]:
a, b = greater_count(sorted_arr1, x), greater_count(sorted_arr2, x)
if a > b:
bisect.insort(sorted_arr1, x)
arr1.append(x)
elif a < b:
bisect.insort(sorted_arr2, x)
arr2.append(x)
elif len(arr1) <= len(arr2):
bisect.insort(sorted_arr1, x)
arr1.append(x)
else:
bisect.insort(sorted_arr2, x)
arr2.append(x)
return arr1 + arr2
提交代码评测得到:耗时2171ms,占用内存34.7MB。