代码如下:
class Solution:
def runeReserve(self, runes: List[int]) -> int:
n = len(runes)
if n <= 1:
return n
runes.sort()
ans = 2
cnt = [1] * n
residue = n - 2
i, j = 0, 1
while j < n and residue > 0:
if runes[j] - runes[i] <= 1 and cnt[i] > 0 and cnt[j] > 0:
cnt[i] -= 1
cnt[j] -= 1
ans += 2
if cnt[i] == 0:
residue -= 1
i = self.findNext(cnt, i, -1)
if cnt[j] == 0:
residue -= 1
j = self.findNext(cnt, j, 1)
else:
if cnt[i] == 0:
i = self.findNext(cnt, i, -1)
elif cnt[j] == 0:
j = self.findNext(cnt, j, 1)
elif cnt[i] <= cnt[j]:
cnt[i] -= 1
ans += 1
if cnt[i] == 0:
residue -= 1
i = self.findNext(cnt, i, -1)
else:
cnt[j] -= 1
ans += 1
if cnt[j] == 0:
residue -= 1
j = self.findNext(cnt, j, 1)
return ans
def findNext(self, cnt, i, d):
j = i + d
while j >= 0 and j < len(cnt) and cnt[j] == 0:
j += d
return j
求问如何修改代码才能正确?需要代码谢谢,其他思路也可以