DW&LeetCode_day14(215、217、230)
寫在前面:
- 昨天一直在看Spring,忘記打卡LeetCode的每日一題了,今天補上吧
開源內容
開源內容
目錄
DW&LeetCode_day14(215、217、230)
寫在前面:
開源內容
學習大綱
215. 陣列中的第K個最大元素
題解:
217. 存在重復元素
題解:
230. 二叉搜索樹中第K小的元素
題解:
學習大綱

215. 陣列中的第K個最大元素
題解:
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return heapq.nlargest(k, nums)[-1] #heapq模板,排序回傳最大K個值

217. 存在重復元素
題解:
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return not len(nums) == len(set(nums))

230. 二叉搜索樹中第K小的元素
題解:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
# 中序遍歷
stack = []
node = root
while node or stack:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
k -= 1
if k == 0:return node.val
node = node.right

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/252684.html
標籤:python
