# 272
class Solution:
def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
def getTree(root,li,k):
if root==None:
return
getTree(root.left,li,k)
if len(li)==k:
if abs(li[0]-target)>abs(root.val-target):
li.pop(0)
li.append(root.val)
else:
return
else:
li.append(root.val)
getTree(root.right,li,k)
li_minTarget=[]
getTree(root,li_minTarget,k)
return li_minTarget
# 273
class Solution:
def numberToWords(self, num: int) -> str:
to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve ' \
'Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split()
tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split()
def helper(num):
if num < 20:
return to19[num - 1:num]
if num < 100:
return [tens[num // 10 - 2]] + helper(num % 10)
if num < 1000:
return [to19[num // 100 - 1]] + ["Hundred"] + helper(num % 100)
for p, w in enumerate(["Thousand", "Million", "Billion"], 1):
if num < 1000 ** (p + 1):
return helper(num // 1000 ** p) + [w] + helper(num % 1000 ** p)
return " ".join(helper(num)) or "Zero"
# 274
class Solution:
def hIndex(self, citations: List[int]) -> int:
citations.sort(reverse = True)
for idx , citation in enumerate(citations):
if idx >= citation:
return idx
return len(citations)
# 275
class Solution:
def hIndex(self, citations: List[int]) -> int:
for idx, citation in enumerate(citations[::-1]):
if idx >= citation:
return idx
return len(citations)
# 276
class Solution:
def numWays(self, n: int, k: int) -> int:
dp = [0] * (n + 3)
dp[1] = k
dp[2] = k * k
for i in range(3 , n + 1):
dp[i] = dp[i - 1] * (k - 1) + dp[i - 2] * (k - 1)
return dp[n]
# 277
class Solution:
def findCelebrity(self, n: int) -> int:
candidate = 0
for x in range(1, n):
if knows(candidate, x) == True:
candidate = x
for x in range(n):
if candidate == x:
continue
if knows(candidate, x) == True:
return -1
if knows(x, candidate) == False:
return -1
return candidate
# 278
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
left = 1
right = n
while left < right:
mid = left + (right - left) // 2
if not isBadVersion(mid):
left = mid + 1
else:
right = mid
return left
# 279
class Solution:
def numSquares(self, n: int) -> int:
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(1 , n + 1):
for j in range(1 , int(n**0.5) + 1):
dp[i] = min(dp[i] , dp[i - j * j] + 1)
return dp[-1]
# 280
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if not nums:
return
i = 0
while i < len(nums) - 1:
if i % 2 == 0 and nums[i] > nums[i + 1]:
nums[i] , nums[i + 1] = nums[i + 1] , nums[i]
elif i % 2 != 0 and nums[i] < nums[i + 1]:
nums[i] , nums[i + 1] = nums[i + 1] , nums[i]
else:
i += 1