35. 搜索插入位置
1 class Solution:
2 def searchInsert(self, nums: List[int], target: int) -> int:
3 left, right = 0, len(nums)-1
4
5 while left <= right: #左闭右闭
6 mid = left + (right-left) // 2
7 if nums[mid] < target:
8 left = mid + 1
9 elif nums[mid] > target:
10 right = mid - 1
11 else:
12 return mid
13
14 return right + 1
34. 在排序数组中查找元素的第一个和最后一个位置
1 class Solution:
2 # 1、首先,在 nums 数组中二分查找 target;
3 # 2、如果二分查找失败,则 binarySearch 返回 -1,表明 nums 中没有 target。此时,searchRange 直接返回 {-1, -1};
4 # 3、如果二分查找成功,则 binarySearch 返回 nums 中值为 target 的一个下标。然后,通过左右滑动指针,来找到符合题意的区间
5 def searchRange(self, nums: List[int], target: int) -> List[int]:
6 def binarySearch(nums:List[int], target:int) -> int:
7 left, right = 0, len(nums)-1
8 while left<=right: # 不变量:左闭右闭区间
9 middle = left + (right-left) // 2
10 if nums[middle] > target:
11 right = middle - 1
12 elif nums[middle] < target:
13 left = middle + 1
14 else:
15 return middle
16 return -1
17 index = binarySearch(nums, target)
18 if index == -1:return [-1, -1] # nums 中不存在 target,直接返回 {-1, -1}
19 # nums 中存在 targe,则左右滑动指针,来找到符合题意的区间
20 left, right = index, index
21 # 向左滑动,找左边界
22 while left -1 >=0 and nums[left - 1] == target: left -=1
23 # 向右滑动,找右边界
24 while right+1 < len(nums) and nums[right + 1] == target: right +=1
25 return [left, right]
69. x 的平方根
1 class Solution:
2 def mySqrt(self, x: int) -> int:
3 # x = 0 或 1 时,直接返回结果
4 if x <= 1:
5 return x
6
7 left, right = 1, x
8 while left <= right:
9 middle = left + (right - left) // 2
10 if middle ** 2 == x:
11 return middle
12 elif middle ** 2 > x:
13 right = middle - 1
14 else:
15 left = middle + 1
16
17 return right
367. 有效的完全平方数
1 class Solution:
2 def isPerfectSquare(self, num: int) -> bool:
3 if num <= 1:
4 return True
5 left, right = 1, num//2
6 while left <= right:
7 mid = left + (right-left)//2
8 if mid ** 2 == num:
9 return True
10 elif mid **2 > num:
11 right = mid - 1
12 else:
13 left = mid + 1
14 return False