力扣第 193 场周赛

一、一维数组的动态和

1、题目描述
力扣第 193 场周赛_第1张图片
在这里插入图片描述

2、题解
利用数组和一次线性扫描,每一次的值等于上一次的值+这次从元素

class Solution:
    def runningSum(self, nums: List[int]) -> List[int]:
        n = len(nums)
        if n < 2:
            return nums
        res = [nums[0]] * n
        for i in range(1,n):
            res[i] = res[i - 1] + nums[i]
        return res

二、不同整数的最少数目

1、题目描述:
力扣第 193 场周赛_第2张图片

2、题解
哈希表+排序

class Solution:
    def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
        hashmap = {}
        n = len(arr)
        for i in range(n):
            if arr[i] not in hashmap:
                hashmap[arr[i]] = 1
            else:
                hashmap[arr[i]] += 1
        # print(hashmap)
        nums = []
        for i,key in enumerate(hashmap):
            nums.append(hashmap[key])
        print(nums)
        nums.sort()
        # print(nums)
        res = len(hashmap)
        for i in nums:
            if i <= k:
                k -= i
                res -= 1
        return res

三、制作 m 束花所需的最少天数

1、题目描述

力扣第 193 场周赛_第3张图片
力扣第 193 场周赛_第4张图片

2、题解

class Solution:
    def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
        #二分查找
        n = len(bloomDay)
        if n < m * k:
            return -1
        left,right = 0,max(bloomDay)
        while left + 1 < right:
            mid = left + (right - left) // 2
            cnt = 0
            temp = 0
            for i in range(n):
                if bloomDay[i] <= mid:
                    cnt += 1
                else:
                    temp += cnt // k
                    cnt = 0
            temp += cnt // k
            if temp >= m:
                right = mid 
            else:
                left = mid
        return right

四、树节点的第 K 个祖先

1、题目描述
力扣第 193 场周赛_第5张图片
力扣第 193 场周赛_第6张图片

2、题解:
动态规划

class TreeAncestor:

    def __init__(self, n: int, parent: List[int]):
        pp = [[0]*n  for _ in range(16)]
        for i in range(n):
            pp[0][i] = parent[i]
        for k in range(1, 16):
            for i in range(n):
                p = pp[k-1][i]
                if p>=0:
                    p = pp[k-1][p]
                pp[k][i]=p
        self.pp = pp


    def getKthAncestor(self, node, k):

        p = node
        for i in range(16):
            if p<0: break;
            if k&(1<<i):
                p = self.pp[i][p];
        return p


# Your TreeAncestor object will be instantiated and called as such:
# obj = TreeAncestor(n, parent)
# param_1 = obj.getKthAncestor(node,k)

你可能感兴趣的:(LeetCode)