![](/img/trans.png)
[英]Efficient solution to find list indices greater than elements in a second list
[英]How to find an order of list such that its elements are greater than the corresponding elements in second list. I have to maximize such number
它沒有通過 11 個測試用例中的一個。
給定 2 個列表,我必須在第一個列表中找到順序,以使第二個列表中的相應元素的量級較小。
例如:如果列表 1 有元素[10, 40, 30]
並且列表 2 有元素[20,5,50]
這里只有列表 1 中的40
大於列表 2 中對應的5
列表 1 中的正確順序到最大化這樣的順序將是[30,40,10]
,現在 2 個元素大於列表 2 中的相應元素。
請注意,它應該嚴格地更大。
我的做法:
t1
並且列表 2 中的元素是t2
,那么如果t1
出現在t2
之后,那么我們就有一個匹配項(因為這個t1
會大於t2
,(我添加了存在相等的情況,在這種情況下,它將簡單地視為t1 = t2
並繼續循環)。 def main(t1,t2):
tn = []
# Make a list of tuples such that each tuple is of the form (number, list it belongs to)
# so if a number belongs to t1, say 5. So the tuple will look like (5,t1)
for i,j in zip(t1,t2):
tn.append((i,'t1'))
tn.append((j,'t2'))
# Sort this tuple on the basis of numbers
tn = sorted(tn, key = lambda a: a[0])
wins = 0
t1_ind = 0
t2_ind = 0
# Implementation of point 3 from here
while True:
if t1_ind > t2_ind: # The t1 index should always be greater than t2 index for a match
if tn[t2_ind][1] == 't2':
# An edge case for equal numbers, these won't be greater even if t1 occurs after t2
if tn[t1_ind][1] == 't1' and tn[t1_ind][0] != tn[t2_ind][0]:
# We have a successful match here and hence we update the win count
wins += 1
t2_ind += 1 # Move t2's index ahead as we have a match
t1_ind += 1 # In any case if we find t2 and do an analysis, t1's index should move ahead
else:
# if we don't find t2 and t2_index, then move ahead
t2_ind += 1
else:
# Update index of t1, as t1's index is <= t2's index now
t1_ind += 1
if t1_ind >= len(tn) - 1:
break
return wins
它的拋出錯誤,我無法弄清楚出了什么問題。 它正在通過 10/11 測試用例。 除了運行需要 4 秒並失敗之外,沒有顯示關於 1 邊緣情況的任何內容
這進入O( n Log n)
。 如果有更好的方法或優化可能,那么我想知道。
我找到了一個類似的帖子,但它在 C++ 並且沒有解釋,所以我無法理解邏輯。 C++ 中的類似問題
編輯:關於我的方法的一些額外要點,因為有些人認為該方法不是直接直觀的。
對於 2 個列表,算法將它們合並並排序。 合並排序后,例如,元素的順序為:
1 3 4 5 5 6....
所以現在,我們存儲哪個元素屬於哪個列表:(列表 1 為 l1,列表 2 為 l2)
l1 l2 l1 l1 l2 l1....
我們現在從左邊開始迭代,尋找l1 occurring after l2
, l1
對應的數字肯定會大於最小不匹配l2
對應的數字,我們貪婪地做這樣的對並增加每個匹配的計數,標記每個匹配一對。
Sort both lists A and B (O(nlogn))
Make indices Aidx = 0, Bidx = 0
While A[Aidx] <= B[Bidx] increment Aidx
When A[Aidx] becomes larger than B[Bidx] - increment "wins" and increment both indices
Repeat until A end (O(n) stage)
代碼
import random
A = [random.randrange(1, 100) for _ in range(random.randrange(3, 10))]
B = [random.randrange(1, 100) for _ in range(random.randrange(3, 10))]
A.sort()
B.sort()
wins = 0
ia = 0
ib = 0
while ia < len(A) and ib < len(B):
while ia < len(A) and A[ia] <= B[ib]:
ia += 1
if ia < len(A):
wins += 1
ia += 1
ib += 1
print(A)
print(B)
print(wins)
[4, 5, 22, 30, 43, 55, 78, 80]
[19, 54, 85, 95]
2
[16, 17, 23, 26, 29, 34, 48, 98]
[6, 43, 65]
3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.