leetcode - 刷题记录-探索初级算法-排序和搜索

  1. 合并两个有序数组
    1. 给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 使 num1 成为一个有序数组。

      说明:
      1. 初始化 nums1 和 nums2 的元素数量分别为 m 和 
      2. 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
    2. class Solution:
          def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
              """
              Do not return anything, modify nums1 in-place instead.
              """
              if m == 0:
                  nums1[:n+1] = nums2
              elif n == 0:
                  pass
              else:
                  i = m-1
                  # nums1
                  j = n-1
                  # nums2
                  for p in range(m+n-1,-1,-1):
      
                      if nums1[i] > nums2[j]:
                          nums1[p] = nums1[i]
                          i = i-1
                      else:
                          nums1[p] = nums2[j]
                          j = j-1
                      if j == -1:
                          break
                      if i == -1:
                          nums1[:p] = nums2[:j+1]
                          break

      通过

  2. 第一个错误的版本

    1. 你是产品经理,目前正在带领一个团队开发新的产品。不幸的是,你的产品的最新版本没有通过质量检测。由于每个版本都是基于之前的版本开发的,所以错误的版本之后的所有版本都是错的。

      假设你有 n 个版本 [1, 2, ..., n],你想找出导致之后所有版本出错的第一个错误的版本。

      你可以通过调用 bool isBadVersion(version) 接口来判断版本号 version 是否在单元测试中出错。实现一个函数来查找第一个错误的版本。你应该尽量减少对调用 API 的次数。

    2. # The isBadVersion API is already defined for you.
      # @param version, an integer
      # @return a bool
      # def isBadVersion(version):
      
      class Solution:
          def firstBadVersion(self, n):
              """
              :type n: int
              :rtype: int
              """
              t1 = 1
              t2 = n
              while 1:
                  test_id = int((t1+t2)/2)
                  tests = [isBadVersion(test_id-1),isBadVersion(test_id)]
                  if tests == [False,True]:
                      return test_id
                  elif tests == [False,False]:
                      t1 = test_id+1
                  elif tests == [True,True]:
                      t2 = test_id-1

      通过

发布了45 篇原创文章 · 获赞 1 · 访问量 8558

猜你喜欢

转载自blog.csdn.net/qq_32110859/article/details/104988201