DW&LeetCode_day14(215、217、230)
Write in front:
- I have been watching Spring yesterday and forgot to check in LeetCode’s daily question. Let’s make up today.
Open source content
table of Contents
DW&LeetCode_day14(215、217、230)
215. The Kth largest element in the array
230. The Kth smallest element in the binary search tree
Study outline
215. The Kth largest element in the array
answer:
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return heapq.nlargest(k, nums)[-1] #heapq模板,排序返回最大K个值
217. Duplicate elements exist
answer:
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return not len(nums) == len(set(nums))
230. The Kth smallest element in the binary search tree
answer:
# 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