2021-08-14 数组:搜索遍历

67 阅读1分钟

2021-08-14 数组:搜索遍历

乘积最大子数组:动归

  • 挖掘几点信息:

    • 除自身以外:即左边乘积*右边乘积
    • 乘积:累乘,可以利用先前结果(用两个变量维护)
    • 记录:直接使用答案数组记录,左至右左边乘积,反之亦然,然后乘以变量即为累积的另一边的成绩。故而至少需要两个数组,无法进行原地覆盖。
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n = len(nums)
        ans = [1]*n
        per, suf = 1, 1
        for i in range(n):
            ans[i] = ans[i] * per
            ans[n-i-1] = ans[n-i-1] * suf
            per = per * nums[i]
            suf = suf * nums[n-i-1]
        return ans

递增的三元子序列

  • 贪心算法:得到一个就霸占一个,直到符合条件为止
class Solution:
    def increasingTriplet(self, nums: List[int]) -> bool:
        one = two = float('inf')
        for three in nums:
            if three > two: return True
            elif three <= one: one = three
            else: two = three
        return False;

搜索二维矩阵Ⅱ

  • 二分法(对应二维的就是划分为四个矩阵,左侧两个矩阵中可能存在比当前元素小的,故而顺着寻找列即可):
class Solution:
    def searchMatrix(self, matrix, target):
        # an empty matrix obviously does not contain `target`
        if not matrix:
            return False

        def search_rec(left, up, right, down):
            if left > right or up > down:
                return False

            elif target < matrix[up][left] or target > matrix[down][right]:
                return False

            mid = left + (right-left)//2

            # Locate `row` such that matrix[row-1][mid] < target < matrix[row][mid]
            row = up
            while row <= down and matrix[row][mid] <= target:
                if matrix[row][mid] == target:
                    return True
                row += 1
            
            return search_rec(left, row, mid-1, down) or search_rec(mid+1, up, right, row-1)

        return search_rec(0, 0, len(matrix[0])-1, len(matrix)-1)
  • 减枝:通过循迹的方式完成
class Solution:
   def searchMatrix(self, matrix, target):
       # an empty matrix obviously does not contain `target` (make this check
       # because we want to cache `width` for efficiency's sake)
       if len(matrix) == 0 or len(matrix[0]) == 0:
           return False

       # cache these, as they won't change.
       height = len(matrix)
       width = len(matrix[0])

       # start our "pointer" in the bottom-left
       row = height-1
       col = 0

       while col < width and row >= 0:
           if matrix[row][col] > target:
               row -= 1
           elif matrix[row][col] < target:
               col += 1
           else: # found it
               return True
       
       return False