學習資料:https://programmercarl.com/陣列理論基礎.html
理解:
雙指標可以同時獲取一個陣列的兩個位置的值
二分查詢:根據區間範圍(左閉右閉、左閉右開)來判斷左右指標比較方式
刷題記錄:
704.二分查詢(左閉右閉則<=,左右指標,middle=left+(right-left)//2, 因為考慮了等號情況所以下一步left=middle+1或right=middle-1)
點選檢視程式碼
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left, right = 0, len(nums)-1
while left <= right:
middle=left + (right-left)//2
if nums[middle]>target:
right=middle-1
elif nums[middle]<target:
left = middle + 1
else:
return middle
return -1
點選檢視程式碼
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
soft=0
slow=0
size=len(nums)
while soft < size:
if nums[soft] != val:
nums[slow] = nums[soft]
slow += 1
soft += 1
return slow
點選檢視程式碼
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
left=0
right = len(nums)-1
k=len(nums)-1
result=[0]*len(nums)
while left <= right:
if nums[left]**2 > nums[right]**2:
result[k]=nums[left]**2
left += 1
else:
result[k]=nums[right]**2
right -= 1
k -= 1
return result