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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

653. Two Sum IV - Input is a BST

發布時間:2023/12/18 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 653. Two Sum IV - Input is a BST 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目來源:
?
自我感覺難度/真實難度:
?
題意:
?
分析:
?
自己的代碼:
class Solution(object):def findTarget(self, root, k):""":type root: TreeNode:type k: int:rtype: bool"""All=self.InOrder(root)Plus=[]#for i in range(All.size()):for i in range(len(All)):for j in range(len(All)):Plus.append(All[i]+All[j])if k in Plus:return Truereturn Falsedef InOrder(self,root):if not root:returnres=[]

res.append(root.val) self.InOrder(root.left)
self.InOrder(root.right)
return res

1.中序遍歷不會,這不是中序遍歷

2.這樣沒有得到中序遍歷

?

代碼效率/結果:
?
優秀代碼:
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object):def findTarget(self, root, k):""":type root: TreeNode:type k: int:rtype: bool"""res = self.inOrder(root)resset = set(res)for num in res:if k != 2 * num and k - num in resset:return Truereturn Falsedef inOrder(self, root):if not root:return []res = []res.extend(self.inOrder(root.left))res.append(root.val)res.extend(self.inOrder(root.right))return res

?

代碼效率/結果:

Runtime:?84 ms, faster than?56.86%?of?Python?online submissions for?Two Sum IV - Input is a BST.

?
優化后的代碼:
class Solution(object):def findTarget(self, root, k):""":type root: TreeNode:type k: int:rtype: bool"""bfs, s = [], set()bfs = [root]for i in bfs:if k - i.val in s:return Trues.add(i.val)if i.left:bfs.append(i.left)if i.right:bfs.append(i.right)return False

Runtime:?108 ms, faster than?33.56%?of?Python?online submissions for?Two Sum IV - Input is a BST.

這個時間測量是不是有問題呢?

反思改進策略:

   1.使重復元素只有一個的辦法:set()

  ? ?2.中序的過程中,一定要res.extend,不然沒保存到內容

轉載于:https://www.cnblogs.com/captain-dl/p/10187712.html

總結

以上是生活随笔為你收集整理的653. Two Sum IV - Input is a BST的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。