search_insert.py 940 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from typing import List
  2. import pytest
  3. def searchInsert(nums: List[int], target: int):
  4. lens = len(nums)
  5. # 普通解法
  6. # if target in nums:
  7. # return nums.index(target)
  8. # else:
  9. # for i in range(lens):
  10. # if target <= nums[i]:
  11. # nums.insert(i, target)
  12. # return i
  13. # return lens
  14. # 二分法
  15. left, right = 0, lens - 1
  16. while left <= right:
  17. mid = left + (right - left) // 2
  18. if nums[mid] == target:
  19. return mid
  20. if nums[mid] < target:
  21. left = mid + 1
  22. else:
  23. right = mid - 1
  24. return left
  25. # print(searchInsert([1,3,5,6], 5))
  26. @pytest.mark.parametrize(
  27. "nums, target, expect",
  28. [
  29. ([1,3,5,6], 0, 0),
  30. ([1,3,5,6], 5, 2),
  31. ([1,3,5,6], 2, 1),
  32. ([1,3,5,6], 7, 4)
  33. ]
  34. )
  35. def test_cases(nums, target, expect):
  36. assert searchInsert(nums, target) == expect