《剑指 Offer(第 2 版)》通行全球的程序员经典面试秘籍。剖析典型的编程面试题,系统整理基础知识、代码质量、解题思路、优化效率和综合能力这 5 个面试要点。
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
zi={}
ans=0
for i in nums:
try:
zi[i]+=1
ans=i
except:zi[i]=1
return ans
剑指 Offer 05. 替换空格
class Solution:
def replaceSpace(self, s: str) -> str:
return s.replace(' ','%20')
剑指 Offer 04. 二维数组中的查找
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
f=False
for i in range(len(matrix)):
k=bisect.bisect_left(matrix[i],target)
# print(k)
try:
if matrix[i][k]==target:
f=True
break
except:
continue
return f
剑指 Offer 06. 从尾到头打印链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
a=[]
while head and head.next:
a.append(head.val)
head=head.next
try:
a.append(head.val)
except:
pass
# print(head.next)
# print(head)
# print(a)
return a[::-1]
class Solution:
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
arr.sort()
return arr[:k]
class Solution:
def nthUglyNumber(self, n: int) -> int:
h=[1]
zi={1:0}
for i in range(n-1):
k=heapq.heappop(h)
for j in [2,3,5]:
a=k*j
if zi.get(a,1):
zi[a]=0
heapq.heappush(h,a)
return heapq.heappop(h)