讨论/技术交流/同样的案例,同样地代码,执行结果不一致/
同样的案例,同样地代码,执行结果不一致

LCP 14. 切分数组

链接https://leetcode-cn.com/problems/qie-fen-shu-zu/

屏幕截图 2021-03-01 002004.jpg

代码

def gongyue(a, b):

  while(b!=0):

    temp = a % b

    a = b

    b = temp

  return a

def fenge(k,j,nums):
    if len(nums)>=2:
        for i in range((len(nums)-1)):
            if gongyue(k,nums[i])>1 and gongyue(j,nums[i+1])>1:
                return True
        return False
    else:
        return True
SUM = 1
class Solution:

    def splitArray(self, nums: List[int]) -> int:        
        global SUM
        if len(nums)==0:
            return SUM
        elif gongyue(nums[0],nums[-1])>1:
            pass
        elif fenge(nums[0],nums[-1],nums[1:-1]):
            SUM = 1 + SUM
        else:
            SUM = 2 + SUM
            splitArray(nums[1:-1])        
        return SUM
共 2 个回复

另外你的代码无法通过这个测试用例:

[197597,26083,231529,216133,22483,74411,89087,218681,863,228421,214463,224863,5737,32941,216103,132689,159737,151241,164309,73643,45121,59981,68821,11197,54679,85213,138727,89657,102769,112121,136573,27059,77351,109891,94229,173617,224443,149531,84979,31013,219409,156749,108233,80107,90173,138899,151057,66683,66683,153911,69959,79451,75407,159319,7411,78571,128717,52057,55799,128201,125353,214763,12071,152657,81199,190391,96779,62659,27997,318559,299113,258691,258031,296713,297533,341477,273271,270659,296479,262693,270287,247769,246781,308509,289031,298559,246439,318713,317773,260879,322237,245851,276623,319237,352589,283463,235111,393203,917327,495371]

1

原因在于 SUM 是全局变量, 你只初始化了一次。因此只有第一个用例是对的。评测下一个用例的时候,SUM初始值不是1.