350
Title description:
Given two arrays, write a function to calculate their intersection.
Example:
Answer:
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
inter = set(nums1) & set(nums2)
l = []
for i in inter:
l += [i] * min(nums1.count(i), nums2.count(i))
return l
378
Title description:
Give you an nxn matrix, in which each row and each column elements are sorted in ascending order, and find the k-th smallest element in the matrix.
Please note that it is the kth smallest element after sorting, not the kth different element.
Example:
Answer:
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
li=[]
for i in matrix:
li+=i
li.sort()
return li[k-1]
540
Title description:
Given an ordered array containing only integers, each element will appear twice, and only one number will appear only once. Find this number.
Example:
Answer:
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
res=0
for i in nums:
res^=i
return res
718
Title description:
For two integer arrays A and B, return the length of the longest sub-array common to the two arrays.
Example:
Answer:
class Solution:
def findLength(self, A: List[int], B: List[int]) -> int:
'''
l1 = len(A)
l2 = len(B)
dp = [[0 for _ in range(l2+1)] for _ in range(l1+1)]
for i in range(1,l1+1):
for j in range(1,l2+1):
if A[i-1] == B[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
return max(max(row) for row in dp)
'''
result = i = 0
if A and B:
a, b, n = ''.join(map(chr, A)), ''.join(map(chr, B)), min(len(A), len(B))
while i + result < n:
if a[i:i+result+1] in b:
result += 1
else:
i += 1
return result
Interview questions 10.05
Title description:
Sparse array search. There is a sorted string array, which is scattered with some empty strings, write a method to find the position of a given string.
Example:
Answer:
class Solution:
def findString(self, words: List[str], s: str) -> int:
#注意非空数组已排序
left,right=0,len(words)-1
while left<=right:
mid=(left+right)//2
tmp=mid
while mid>=left and words[mid]=='':
mid-=1
if words[mid]==s:
return mid
elif words[mid]>s:
right=mid-1
else:
left=tmp+1
return -1