二分查找
leetcode704 Binary Search
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
class Solution:
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums)-1
while left <= right:
middle = (left+right) // 2
if target > nums[middle]:
left = middle + 1
elif target < nums[middle]:
right = middle -1
else:
return middle
else:
return -1
注意,如果用C++或者java可能会导致overflow,所以需要把修改 middle = (left+right) // 2改成 middle = left+(right-left)//2
视频讲解: Youtube视频讲解
Leetcode977有序数组的平方
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
result = [] #记住初始化
left= 0
right =len(nums)-1
while left <= right: #python中的<=需要写在一起
if nums[left] * nums[left] > nums[right] *nums[right]:
result.append(nums[left] * nums[left])
left +=1
else:
result.append(nums[right] *nums[right])
right-=1
return result[::-1] #reverse
参考资料:Youtube视频讲解