二分法:有序数组不重复(时间复杂度O(log(n))
判断条件(while(left <= right),截取的是[左闭,右闭]区间,根据题目要求选择自己需要的边界值)
第704题:基本二分查找
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0;
right = len(nums) - 1;
while(left <= right):
middle = int((left + right) // 2);
if nums[middle] == target:
return middle;
elif nums[middle] < target:
left = middle + 1;
else:
right = middle - 1;
return -1;
第35 题:搜索插入
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
left , right = 0, len(nums) - 1;
while (left <= right):
middle = int((left + right) / 2);
if nums[middle] == target:
return middle;
elif nums[middle] < target:
left = middle + 1;
else:
right = middle - 1;
return right + 1;
第 69 题:求 X 的平方根
class Solution:
def mySqrt(self, x: int) -> int:
left = 0;
right = x;
while(left <= right):
middle = (right + left) // 2;
y = middle*middle;
if y > x:
right = middle - 1;
else:
left = middle + 1;
return left - 1;
第367题:判断num是否是完全平方数
class Solution:
def isPerfectSquare(self, num: int) -> bool:
left = 0;
right = num;
while (left <= right):
middle = (right + left) // 2;
y = middle * middle;
if y > num:
right = middle - 1;
elif y < num:
left = middle + 1;
else:
return True;
return False