167. Two Sum II - Input Array Is Sorted刷题笔记

初版代码超时,因为遇到一堆很多重复序列

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        for i in range(len(numbers)-1):
            diff = target-numbers[i]
            for j in range(i+1,len(numbers)):
                if numbers[j] == diff:
                    return [i+1,j+1]
                elif numbers[j] >diff:
                    break

因此加上剪枝判断之后,就通过了

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:

        for i in range(len(numbers)-1):
            if i > 0 and numbers[i] == numbers[i-1]:
                continue
            diff = target-numbers[i]
            for j in range(i+1,len(numbers)):
                if j > i+2 and numbers[j] == numbers[j-1]:
                    continue
                
                if numbers[j] == diff:
                    return [i+1,j+1]
                elif numbers[j] >diff:
                    break

167. Two Sum II - Input Array Is Sorted刷题笔记_第1张图片

你可能感兴趣的:(tensor,python,leetcode,算法,职场和发展)