DW&LeetCode_day14(215、217、230)
写在前面:
- 昨天一直在看Spring,忘记打卡LeetCode的每日一题了,今天补上吧
开源内容
目录
DW&LeetCode_day14(215、217、230)
学习大纲
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