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。
博客围绕Leetcode 3072题展开,探讨解题思路,认为该题虽被划分为hard,但只需按题意构造和,难点在于函数实现,构造有序和可快速得结果。还给出Python代码实现,评测显示耗时2171ms,占用内存34.7MB。
729

被折叠的 条评论
为什么被折叠?



