一开始看leetcode,以为algorithm很难,但刷codewars的算法题时,觉得不太难呀。
现在刷leetcode,觉得也还行,很多题目还是可以想出来的。
搜索二维矩阵 II
Aim:一个矩阵(matrix)的每行/每列都按照从小到大的顺序排列,找matrix中是否有target这个数。
笔记:既然矩阵顺序排列,则可采用二分搜索🔍,;在对角线上迭代,二分搜索行和列。
class Solution:
def binary_search(self,matrix,target,start,vertical):
# lo/hi/mid都是index,不是value
#vertical代表搜索一列数据
lo=start
hi=len(matrix)-1 if vertical else len(matrix[0])-1
while hi>=lo:
mid=(lo+hi)//2
if vertical:
if target>matrix[mid][start]:
lo=mid+1
elif target<matrix[mid][start]:
hi=mid-1
else:
return True
else:
if target>matrix[start][mid]:
lo=mid+1
elif target<matrix[start][mid]:
hi=mid-1
else:
return True
return False
def searchMatrix(self, matrix, target):
if not matrix:
return False
else:
for i in range(min(len(matrix),len(matrix[0]))):
horizon_result=self.binary_search(matrix,target,i,False)
vertical_result=self.binary_search(matrix,target,i,True)
if horizon_result or vertical_result:
return True
return False
合并两个有序数组
Aim:给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
笔记:最朴素的解法就是将两个数组合并之后再排序。该算法时间复杂度较差,为O((n + m)log(n + m))。这是由于这种方法没有利用两个数组本身已经有序这一点。
另一种方法:双指针法,空间换时间。将指针p1 置为 nums1的开头, p2为 nums2的开头,在每一步将最小值放入输出数组中。时间复杂度为O(n+m)。
1⃣️
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
nums=nums1[:m]+nums2
nums1[:]=sorted(nums)#nums1[:]而不是nums1
2⃣️
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
#使得空间复杂度由O(1)变为O(m)
nums1_copy=nums1[:m]
nums1[:]=[]#nums1[:],如果是nums1则会发生错误。。。🙅,don‘t know why
p1,p2,i=0,0,0
while p1<m and p2<n:
if nums1_copy[p1]>nums2[p2]:
nums1.append(nums2[p2])
p2+=1
i+=1
else:
nums1.append(nums1_copy[p1])
p1+=1
i+=1
# 如果有一个数组没遍历完
if p1<m:
nums1[i:i+m-p1]=nums1_copy[p1:m]
if p2<n:
nums1[i:i+n-p2]=nums2[p2:n]