面試題3:陣列中重複數字
# 使用set,時間複雜度o(n),空間複雜度o(n)class
solution(object):
deffindrepeatnumber(self, nums):
""":type nums: list[int]
:rtype: int
"""a =set()
for num in
nums:
if num in
a:
return
num a.add(num)
#桶思想,時間複雜度o(n),空間複雜度o(1)
class
solution(object):
deffindrepeatnumber(self, nums):
""":type nums: list[int]
:rtype: int
"""for i in
range(len(nums)):
val =nums[i]
if val != i and val ==nums[val]:
return
val nums[i], nums[val] = nums[val], nums[i]
面試題4:二維陣列中的查詢
#從右上往左下推
class
solution(object):
deffindnumberin2darray(self, matrix, target):
""":type matrix: list[list[int]]
:type target: int
:rtype: bool
"""if matrix == or matrix ==:
return
false
c = len(matrix[0])-1l =0
while
true:
if matrix[l][c] ==target:
return
true
if matrix[l][c] >target:
c -= 1
else
: l += 1
if l > len(matrix)-1 or c <0:
return false
面試題5:替換空格
classsolution(object):
defreplacespace(self, s):
""":type s: str
:rtype: str
"""l = [''] *len(s)
for i in
range(len(s)):
if s[i] == '':
l[i] = '
%20'
else
: l[i] =s[i]
return
''.join(l)
面試題6:從尾到頭列印鍊錶
#非遞迴class
solution(object):
defreverseprint(self, head):
""":type head: listnode
:rtype: list[int]
"""result =
while
head:
head =head.next
return result[::-1]
#遞迴class
solution(object):
defreverseprint(self, head):
""":type head: listnode
:rtype: list[int]
"""result =
defhelper(root):
ifnot
root:
return
helper(root.next)
helper(head)
return result
面試題7:重建二叉樹
classsolution(object):
defbuildtree(self, preorder, inorder):
""":type preorder: list[int]
:type inorder: list[int]
:rtype: treenode
"""def
helper(inc_start, inc_end):
if inc_start ==inc_end:
return
none
inc_value =preorder[self.pre_index]
root =treenode(inc_value)
self.pre_index += 1root.left =helper(inc_start, inc_value_map[inc_value])
root.right = helper(inc_value_map[inc_value] + 1, inc_end)
return
root
self.pre_index =0
inc_value_map =
return helper(0, len(inorder))
面試題9:用兩個棧實現佇列
classcqueue(object):
def__init__
(self):
self.l1 =
self.l2 =
def
""":type value: int
:rtype: none
"""
defdeletehead(self):
""":rtype: int
"""if
notself.l1:
ifnot
self.l2:
return -1
for i in
range(len(self.l2)):
return self.l1.pop()
面試題10-i:斐波那契數列
classsolution(object):
deffib(self, n):
""":type n: int
:rtype: int
"""if n ==0:
return
0 a =0
b = 1
while n != 1:
a, b = b, a+b
n -= 1
return b % 1000000007
面試題10-ii:青蛙跳台階問題
classsolution(object):
defnumways(self, n):
""":type n: int
:rtype: int
"""if n ==0:
return 1a = 1b = 1
while n != 1:
a, b = b, a+b
n -= 1
return b % 1000000007
劍指 offer 刷題記錄
任誰都躲不過找工作的問題,好希望能多準備一些時間,奈何時間不等人,每天刷幾道題,並且記錄下來吧 def replacespace s write code here num space 0 new s for i in range len s if i num space 1 for i in ra...
劍指offer刷題記錄
遞迴法 鍊錶的後續遍歷,並用self.k來記錄倒數節點的位置,找到了就返回找到的節點,否則返回none coding utf 8 class listnode def init self,x self.val x self.next none class solution def init self...
劍指offer刷題記錄 綜合
將乙個字串轉換成乙個整數,要求不能使用字串轉換整數的庫函式。數值為0或者字串不是乙個合法的數值則返回0 輸入描述 輸入乙個字串,包括數字字母符號,可以為空 輸出描述 如果是合法的數值表達則返回該數字,否則返回0 做這個題目做的真的很煩,最麻煩的就是判斷當前是否越界。可儲存的最大的正數末位為7,可儲存...