3072. Allocate elements into two arrays II.md
topic:
3072. Allocate elements into two arrays II.md """
Thought:
-
initialization: 首先Will nums Array反转,以便我们可以从最后一个元素start处理。这一步exist最初与学长@Angro beatICPCI learned,
pop()Comparepop(0)It is much faster。 Will反转后的第一个元素分配给 arr1 and temp1,The second element is allocated to arr2 and temp2。 -
Iteration processing each element: use while Traversal nums Array的剩余元素。 For each element,use bisect.bisect_right exist arr1 and arr2 middle找到Compare当前元素小的元素的数量。 Re -uselen(arr1)andlen(arr2)Minus this quantity,得到Compare当前元素大的元素的数量。 然后进行Compare较To。 为了use二分查找,therefore我们要保证 arr1 and arr2 yes有序的, Pythonmiddleuse
insort()To。 but同时我们要维持一个答案Array,thereforeappendTo。 -
Merge answer
Code:
import bisect
from typing import List
class Solution:
def resultArray(self, nums: List[int]) -> List[int]:
nums = nums[::-1]
temp = nums.pop()
arr1 = [temp]
temp1 = [temp]
temp = nums.pop()
arr2 = [temp]
temp2 = [temp]
while nums:
temp = nums.pop()
# [28] [2]
index1 = bisect.bisect_right(arr1, temp)
index2 = bisect.bisect_right(arr2, temp)
length_1 = len(arr1) - index1
length_2 = len(arr2) - index2
if length_1 > length_2:
bisect.insort(arr1, temp)
temp1.append(temp)
elif length_1 < length_2:
bisect.insort(arr2, temp)
temp2.append(temp)
else:
if len(arr1) > len(arr2):
bisect.insort(arr2, temp)
temp2.append(temp)
else:
bisect.insort(arr1, temp)
temp1.append(temp)
return temp1 + temp2贡献者
这篇文章有帮助吗?
最近更新
Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0