感悟: 这两道题其实都是在利用好双指针的特点
二分查找(704)
因为给定的整数数组时有序的,所以除了暴力search之外时存在加速的可能的,使用二分法可以比较好的消除一些冗余部分的比较判断;
这种写法是考虑左闭区间,右闭区间的;
复杂度分析:o(log(n))
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums)-1 # 因为数组下标是从0开始的,所以要做长度减一
while left <= right: # 区间的左边肯定小于右边的
middle = (right+ left) //2
if target == nums[middle]: # 找到了中间位置判断是否等于target
return middle
elif target < nums[middle]: # 若target 小于,说明如果存在在左边区间里,那么右指针需要移动
right = middle-1
else: #否则就是移动左指针了,这里使用了+1/-1其实就可以有效的遍历完整个区间
left = middle+1
return -1
移除元素(27)
最开始有个误区就是直接用nums.remove(obj); 可是如果for循环,这里remove元素后,数组的长度就是会变化,那么自然后面容易out of index的错误了
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
count = 0
for i in range(len(nums)):
if nums[i]!=val:
nums[count]=nums[i]
count +=1
return count
有进一步看了解析才理解这里说的双指针的妙用,就是一个快指针,一个慢指针,快指针就是for循环中的i去遍历整个数组,慢指针就是这里的count表示不被移除的数