讨论/题目交流/Pycharm 上提交同一测试用例结果不一致/
Pycharm 上提交同一测试用例结果不一致

简介

力扣第55题中,对测试用例[3,2,1,0,4],我在Pycharm上能得到false,但在网站提交时确显示为true,不明白为什么,用的Python语言,求解答谢谢。

代码

    def canJump(self, nums):
        end = len(nums) - 1
        nowindex = 0
        flag = ''

        while True:
            if nowindex >= end:
                flag = 'true'
                break
            if nums[nowindex] == 0 and nowindex != end:
                flag = 'flase'
                break
            temp = nums[nowindex:nowindex+nums[nowindex]]
            if temp:
                max = 0 + temp[0]
                nowindex = nowindex + temp[0]
                for ind,val in enumerate(temp):
                    if ind + val > max:
                        nowindex = nowindex + val
                        max = ind + max
            else:
                nowindex = nowindex + 1

        return flag
if __name__ == "__main__":
        ss = Solution()
        num1 = [3,2,1,0,4]
        print(ss.canJump(num1))]
展开讨论

上面的代码有问题,下面的是通过测试的。

class Solution:
    def canJump(self, nums):
        lennums = len(nums)
        if lennums == 1:
            return True
        if 0 not in nums:
            return True
        if nums[0] == 0:
            return False
        if nums.index(0) == lennums - 1:
            return True
        zerosindex = []
        for ind,val in enumerate(nums):
            if val == 0:
                zerosindex.append(ind)
        nowindex = 0
        lenzerosindex = len(zerosindex)
        while nums:
            if 0 not in nums:
                return True
            zeroindex = zerosindex[0]
            nextindex = zeroindex
            prezero = nums[0:zeroindex]
            lengthnums = len(nums)
            max = -1
            for ind,val in enumerate(prezero):
                if prezero[ind] + ind + 1 >= lengthnums:
                    return True
                else:

                    for zerind in zerosindex:
                        if prezero[ind] + ind > zerind:
                            if zerind > max:
                                max = zerind


            if max == -1:
                return False

            nums = nums[max+1:]
            zerosindex = []
            for ind, val in enumerate(nums):
                if val == 0:
                    zerosindex.append(ind)
 

if __name__ == "__main__":
        ss = Solution()
        num1 = [3,0,8,2,0,0,1]
        print(ss.canJump(num1))



展开全部 3 讨论