关于python#代码#的问题,如何解决?

img


代码如下:


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

求问如何修改代码才能正确?需要代码谢谢,其他思路也可以

这个题目,思路就很简单,求连续递增不超过1的最大长度,用一个指针,一个记录,两个变量即可

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632