日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

算法(20)-leetcode-剑指offer4

發(fā)布時間:2023/12/13 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 算法(20)-leetcode-剑指offer4 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

leetcode-劍指offer-4

  • 33.面試題33-二叉搜索樹的后序遍歷序列
  • 34.面試題34-二叉樹中和為某一值的路徑
  • 35.面試題35-復(fù)雜鏈表的復(fù)制
  • 36.面試題36-二叉搜索樹與雙向鏈表
  • 37.面試題37-序列化二叉樹
  • 38.面試題38-字符串的排列
  • 39.面試題39-數(shù)組中出現(xiàn)次數(shù)超過一半的數(shù)字
  • 40.面試題40-最小的k個數(shù)
  • 41.面試題41-數(shù)據(jù)流中的中位數(shù)
  • 42.面試題42-連續(xù)子數(shù)組的最大和

本系列博文為題庫刷題筆記,(僅在督促自己刷題)如有不詳之處,請參考leetcode官網(wǎng):https://leetcode-cn.com/problemset/lcof/

33.面試題33-二叉搜索樹的后序遍歷序列

輸入一個整數(shù)數(shù)組,判斷該數(shù)組是不是某二叉搜索樹的后序遍歷結(jié)果。如果是則返回 true,否則返回 false。假設(shè)輸入的數(shù)組的任意兩個數(shù)字都互不相同。

參考思路1:如果所有的子樹都是二叉搜索樹,那么此序列為二叉搜索樹的后序遍歷序列。
step1:確定左右子樹區(qū)間,對左右子樹區(qū)間再遞歸調(diào)用判斷函數(shù),遞歸函數(shù)的出口是,沒有可以判斷的節(jié)點(區(qū)間為空)
key:確定左右子樹區(qū)間的方法:二叉搜索樹左子樹節(jié)點都小于根節(jié)點,右子樹節(jié)點都大于根節(jié)點。

class Solution(object):def verifyPostorder(self, postorder):""":type postorder: List[int]:rtype: bool"""def rec(i,j):if i>=j: # 右邊界出口 i>j ,左邊界出口,i== jreturn Truem=i # i == 0, j == n-1while(postorder[m]<postorder[j]): # i,m-1 左子樹,m,j-1右子樹 遞歸判斷m+=1p=mwhile(postorder[p]>postorder[j]):p+=1return p==j and rec(i,m-1) and rec(m,j-1)return rec(0,len(postorder)-1)

34.面試題34-二叉樹中和為某一值的路徑

輸入一棵二叉樹和一個整數(shù),打印出二叉樹中節(jié)點值的和為輸入整數(shù)的所有路徑。從樹的根節(jié)點開始往下一直到葉節(jié)點所經(jīng)過的節(jié)點形成一條路徑。

由頂向下的遞歸,查找最后的葉子節(jié)點對應(yīng)的匹配數(shù)是否為葉子值。如果對應(yīng)的值匹配上,可以往結(jié)果添加一條新的路徑。

# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution(object):def pathSum(self, root, sum):""":type root: TreeNode:type sum: int:rtype: List[List[int]]"""def top_down(node,target):if node==None:returnpath.append(node.val)if node.left==None and node.right==None:if node.val==target:res.append(list(path)) # 直接res.append(path)加上的是[]top_down(node.left,target-node.val)top_down(node.right,target-node.val)path.pop()res,path=[],[]top_down(root,sum)return res

路徑總和的擴展,路徑總和要判斷是否存一條路徑,只要存在就行,不需要具體路徑,這個需要列舉所有的路徑。

35.面試題35-復(fù)雜鏈表的復(fù)制

請實現(xiàn) copyRandomList 函數(shù),復(fù)制一個復(fù)雜鏈表。在復(fù)雜鏈表中,每個節(jié)點除了有一個 next 指針指向下一個節(jié)點,還有一個 random 指針指向鏈表中的任意節(jié)點或者 null。
思路:依據(jù)原鏈表新建一個新鏈表很簡單,難點:隨機指針的指向。需要記錄一張新鏈表節(jié)點和原鏈表節(jié)點的hash表。重新遍歷一遍原鏈表之找到新鏈表中對應(yīng)的鏈接節(jié)點。

""" # Definition for a Node. class Node:def __init__(self, x, next=None, random=None):self.val = int(x)self.next = nextself.random = random """ class Solution(object):def copyRandomList(self, head):""":type head: Node:rtype: Node"""if head==None:return headhas_map={}res_head=Node(0)res_curr=res_headori_curr=headwhile(ori_curr):res_curr.next=Node(ori_curr.val,None,None)has_map[ori_curr]=res_curr.nextres_curr=res_curr.nextori_curr=ori_curr.nextori_curr=headres_curr=res_head.nextwhile(ori_curr):if ori_curr.random:res_curr.random=has_map[ori_curr.random]ori_curr=ori_curr.nextres_curr=res_curr.nextreturn res_head.next

36.面試題36-二叉搜索樹與雙向鏈表

輸入一棵二叉搜索樹,將該二叉搜索樹轉(zhuǎn)換成一個排序的循環(huán)雙向鏈表。要求不能創(chuàng)建任何新的節(jié)點,只能調(diào)整樹中節(jié)點指針的指向。
特別地,我們希望可以就地完成轉(zhuǎn)換操作。當轉(zhuǎn)化完成以后,樹中節(jié)點的左指針需要指向前驅(qū),樹中節(jié)點的右指針需要指向后繼。還需要返回鏈表中的第一個節(jié)點的指針。

參考題解:
step1.二叉搜索樹中序遍歷為遞增序列,采用中序遍歷遍歷二叉搜索樹。
step2.構(gòu)建相鄰節(jié)點:前驅(qū)節(jié)點pre_node 當前節(jié)點curr_node,為了構(gòu)成雙向鏈表,要使得pre_node.right=curr_node, curr_node.left=pre_node (重新定向節(jié)點左右所指向的節(jié)點,完成4到3的鏈接)
step3.鏈表頭節(jié)點和尾部節(jié)點:head.left=tail,tail.right=head

""" # Definition for a Node. class Node(object):def __init__(self, val, left=None, right=None):self.val = valself.left = leftself.right = right """ class Solution(object):def __init__(self):self.pre_node=Noneself.head=Nonedef treeToDoublyList(self, root):""":type root: Node:rtype: Node"""def dfs(cur_node):if cur_node==None:returndfs(cur_node.left)if self.pre_node:self.pre_node.right=cur_nodecur_node.left=self.pre_nodeelse:self.head=cur_nodeself.pre_node=cur_nodedfs(cur_node.right)if root==None:return rootdfs(root)self.head.left=self.pre_nodeself.pre_node.right=self.headreturn self.head

37.面試題37-序列化二叉樹

請實現(xiàn)兩個函數(shù),分別用來序列化和反序列化二叉樹。
本題與主站 297 題相同:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
注意點:序列化和反序列化的遍歷方式是一樣的。

class Codec:def serialize(self, root):"""Encodes a tree to a single string.:type root: TreeNode:rtype: str"""global stringdef dfs_pre_ser(node):global stringif node==None:string+="None,"returnstring+="{0},".format(node.val)dfs_pre_ser(node.left)dfs_pre_ser(node.right)string=""dfs_pre_ser(root)return stringdef deserialize(self, data):"""Decodes your encoded data to tree.:type data: str:rtype: TreeNode"""def dfs_pre_deser(lis):if lis[0]=="None": # 最右邊葉子節(jié)點的右兒子也是none,操作完lis.pop(0)return Nonenode=TreeNode(int(lis[0]))lis.pop(0)node.left=dfs_pre_deser(lis)node.right=dfs_pre_deser(lis)return nodedata_lis=data.split(",")return dfs_pre_deser(data_lis)

38.面試題38-字符串的排列

輸入一個字符串,打印出該字符串中字符的所有排列。
你可以以任意順序返回這個字符串數(shù)組,但里面不能有重復(fù)元素。
思路:回溯問題,注意維護當選擇路徑,遍歷選擇列表,撤銷路徑,
本質(zhì)是一個遞歸問題,再稍加注意遞歸出口
注意:字符串中可能包含相同字符,所以要維護一個已有路徑列表(直接用結(jié)果列表所搜很慢,維護一個hash 表時間快了40倍),只有當路徑不存在時才加入最后的答案中。

class Solution(object):def permutation(self, s):""":type s: str:rtype: List[str]"""def rec(lis,path):if lis==[]:if not path_hash.get(path):res.append(path)path_hash[path]=Truereturnfor i in range(len(lis)):# 一句話完成了:選擇做選擇path+lis[i],選擇列表更新lis[:i]+lis[i+1:],語句結(jié)束時候,path 還是原來的path,即實現(xiàn)撤銷選擇rec(lis[:i]+lis[i+1:],path+lis[i]) res=[]s_lis=[]path_hash={}for char in s:s_lis.append(char)rec(s_lis,"")return res

39.面試題39-數(shù)組中出現(xiàn)次數(shù)超過一半的數(shù)字

數(shù)組中有一個數(shù)字出現(xiàn)的次數(shù)超過數(shù)組長度的一半,請找出這個數(shù)字。
你可以假設(shè)數(shù)組是非空的,并且給定的數(shù)組總是存在多數(shù)元素。
暴力統(tǒng)計:每個數(shù)字都統(tǒng)計一次,時間復(fù)雜度o(n^2)
維護一hash 表,對應(yīng)鍵值對為:數(shù)值:出現(xiàn)次數(shù),最后統(tǒng)計出現(xiàn)次數(shù)最大的即可。(題目說存在這樣一個數(shù)字)

class Solution(object):def majorityElement(self, nums):""":type nums: List[int]:rtype: int"""count_has={}for val in nums:if not count_has.get(val):count_has[val]=1else:count_has[val]+=1return max(count_has.keys(),key=count_has.get)# count_has.keys()獲取所有的值,# ‘key=’為max 函數(shù)的參數(shù)

40.面試題40-最小的k個數(shù)

思路1:最小排序排k次,時間復(fù)雜度o(nk)
35/38,時間超出限制

class Solution(object):def getLeastNumbers(self, arr, k):""":type arr: List[int]:type k: int:rtype: List[int]"""n=len(arr)for i in range(k):for j in range(i+1,n):if arr[i]>arr[j]:arr[i],arr[j]=arr[j],arr[i]return arr[:k]

思路2:快排序,時間復(fù)雜度o(nlogn)

class Solution(object):def getLeastNumbers(self, arr, k):""":type arr: List[int]:type k: int:rtype: List[int]"""# arr.sort()# 自己寫一遍快排序def quick_sort(i,j,nums,flag):if i<j:p=partition(i,j,nums)quick_sort(i,p-1,nums,flag+1)quick_sort(p+1,j,nums,flag+1)def partition(l,r,nums): # 分區(qū)pivort=nums[l]while(l<r):while(l<r and nums[r]>pivort):r-=1# 跳出循環(huán)的情況是l=r or nums[r]<=pivort, 將nums[r] 放到l 指示的位置nums[l]=nums[r] # 每個數(shù)在寫進去之前已經(jīng)被拿走了。while(l<r and nums[l]<=pivort):l+=1# 跳出循環(huán)的情況是l=r or nums[l]>pivort, 將nums[l] 放到r 指示的位置nums[r]=nums[l]nums[l]=pivortreturn lquick_sort(0,len(arr)-1,arr,1)return arr[:k]

41.面試題41-數(shù)據(jù)流中的中位數(shù)

如何得到一個數(shù)據(jù)流中的中位數(shù)?如果從數(shù)據(jù)流中讀出奇數(shù)個數(shù)值,那么中位數(shù)就是所有數(shù)值排序之后位于中間的數(shù)值。如果從數(shù)據(jù)流中讀出偶數(shù)個數(shù)值,那么中位數(shù)就是所有數(shù)值排序之后中間兩個數(shù)的平均值。
例如,
[2,3,4] 的中位數(shù)是 3
[2,3] 的中位數(shù)是 (2 + 3) / 2 = 2.5
設(shè)計一個支持以下兩種操作的數(shù)據(jù)結(jié)構(gòu):
void addNum(int num) - 從數(shù)據(jù)流中添加一個整數(shù)到數(shù)據(jù)結(jié)構(gòu)中。
double findMedian() - 返回目前所有元素的中位數(shù)。

要找中位數(shù),就要維護一個有序結(jié)構(gòu),當數(shù)字插入時,維護至有序位置。在查詢中位數(shù)時直接返回:
難點:維護有序位置–兩個頂堆(頂堆,用list存完全二叉樹,樹根節(jié)點值最大或最小)
Python 中 heapq 模塊是小頂堆。實現(xiàn) 大頂堆 方法: 小頂堆的插入和彈出操作均將元素 取反 即可。

from heapq import * class MedianFinder(object):def __init__(self):"""initialize your data structure here."""self.A=[]self.B=[]def addNum(self, num):""":type num: int:rtype: None"""if len(self.A)!=len(self.B):heappush(self.A,num)heappush(self.B,-heappop(self.A))else:heappush(self.B,-num)heappush(self.A,-heappop(self.B))def findMedian(self):""":rtype: float"""if len(self.A)!=len(self.B):return self.A[0]else:return (self.A[0]-self.B[0])/2.0

42.面試題42-連續(xù)子數(shù)組的最大和

輸入一個整型數(shù)組,數(shù)組里有正數(shù)也有負數(shù)。數(shù)組中的一個或連續(xù)多個整數(shù)組成一個子數(shù)組。求所有子數(shù)組的和的最大值。要求時間復(fù)雜度為O(n)。
核心要點:負數(shù)前綴不能要!!!

class Solution(object):def maxSubArray(self, nums):""":type nums: List[int]:rtype: int"""mid_sum=0max_sum=float("-INF")for val in nums:mid_sum+=valmax_sum=max(mid_sum,max_sum) # mid_sum寫在歸零的上方,防止最大和為負數(shù)的情況if mid_sum<0:mid_sum=0return max_sum

總結(jié)

以上是生活随笔為你收集整理的算法(20)-leetcode-剑指offer4的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。