Re: [閒聊] leetcode 大師請進已回收
def find_LIS_indices(nums):
dp = []
back = {}
for num in nums:
if not dp or dp[-1] < num:
back[num] = 0 if not dp else dp[-1]
dp.append(num)
else:
idx = bisect_left(dp, num)
dp[idx] = num
back[num] = dp[idx-1] if idx != 0 else 0
for i in range(len(dp)-1, 0, -1):
dp[i-1] = back[dp[i]]
return set(dp)
def min_actions(arr):
res = []
lis = []
left = []
s = find_LIS_indices(arr)
#print(s)
for num in arr:
if num in s:
lis.append(num)
else:
left.append(num)
left.sort()
lisi, lisn = 0, len(lis)
for i in range(len(left)):
while lisi < lisn and lis[lisi] < left[i]:
lisi += 1
res.append((left[i], lis[lisi-1]))
lis[lisi-1] = left[i]
return res
print(min_actions([1, 3, 7, 9, 5, 2])) # [(2, 5), (0, 2)]
print(min_actions([9, 7, 5, 3, 1])) # [(5, 9), (4, 7), (3, 5), (2, 3)]
print(min_actions([3, 2, 1])) # [(3, 3), (2, 2)]
print(min_actions([1, 7, 9, 2, 3, 4])) # [(6, 9), (5, 7)]
print(min_actions([1, 7, 9, 2]))
print(min_actions([1, 7, 9, 2, 5, 6, 3, 8, 10]))
Output:
[(2, 1), (5, 3)]
[(3, 1), (5, 3), (7, 5), (9, 7)]
[(2, 1), (3, 2)]
[(7, 4), (9, 7)]
[(2, 1)]
[(3, 2), (7, 6), (9, 8)]
用Rushia的改了一下 找LIS 和後面插入應該直接用數字代表就好?
--
蛤?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.164.140.99 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715011465.A.221.html
→
05/07 00:09,
6月前
, 1F
05/07 00:09, 1F
推
05/07 00:10,
6月前
, 2F
05/07 00:10, 2F
→
05/07 00:10,
6月前
, 3F
05/07 00:10, 3F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 6 之 8 篇):