给两个字符串s和t,判断t是否为s的重新排列后组成的单词。 s = “anagram”, t = “nagaram”, return true. s = “rat”, t = “car”, return false
# function 1 O(nlogn) 排序deffunc1(s, t):
s =list(s)
t =list(t)
s.sort()
t.sort()return s == t
# function 2 O(nlogn) 排序deffunc2(s, t):returnsorted(s)==sorted(t)# function 3 O(n) 计数deffunc3(s, t):
dict1 =dict()
dict2 =dict()for i in s:
dict1[i]= dict1.get(i,0)+1for j in t:
dict2[j]= dict2.get(j,0)+1return dict1 == dict2
# function 1 O(n^2)deffunc1(matrix, target):for line in matrix:if target in line:returnTruereturnFalse# function 2 O(logn)deffunc2(matrix, target):
h, w =len(matrix),len(matrix[0])'''
0,1,2
3,4,5
6,7,8
'''if h ==0:returnFalseif w ==0:returnFalse
left =0
right = w * h -1while left <= right:
mid =(left + right)
i = mid // w
j = mid % w
if matrrix[i][j]== target:returnTrueelif matrix[i][j]> target:
right = mid -1else:
left mid +1else:returnFalse