leetcode 第 84 场双周赛





简单题,用dict遍历统计后,排序得出结果

class Solution:
    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:
        res={
          
   }
        for it1 in items1:
            if res.get(it1[0]):
                res[it1[0]]+=it1[1]
            else:
                res[it1[0]]=it1[1]
        
        for it2 in items2:
            if res.get(it2[0]):
                res[it2[0]]+=it2[1]
            else:
                res[it2[0]]=it2[1]
        res= sorted(res.items(), key=lambda x:x[0]) 
        

        return res

然后是大佬的一行解法(太优雅了)

class Solution:
    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:
        return sorted((Counter(dict(items1)) + Counter(dict(items2))).items())


一般这种题要么计算坏数对数,要么计算好数对数,这边计算好数对数后,在总数上减去即可

class Solution:
    def countBadPairs(self, nums: List[int]) -> int:
        n, cnt = len(nums), defaultdict(int)
        res = 0
        for step, num in enumerate(nums):
            res += cnt[num - step]  
            cnt[num - step] += 1
        return n * (n - 1) // 2  - res


简单的调度模拟

class Solution:
    def taskSchedulerII(self, tasks: List[int], space: int) -> int:
        res=1
        vis={
          
   }
        vis[tasks[0]]=1
        for i in range(1,len(tasks)):
            if vis.get(tasks[i]) and res-vis[tasks[i]]<=space:
                res = vis[tasks[i]]+space+1
                vis[tasks[i]]=res             
            else:
                res += 1
                vis[tasks[i]]=res
        return res


一开始想着从后往前遍历,然后周围没有纸和笔打草稿,只能硬想,最后还是看大佬题解才反应过来 (下次写题一定得带上纸笔)

class Solution:
    def minimumReplacement(self, nums: List[int]) -> int:
        cnt, m = 0, nums[-1]
        for num in reversed(nums):
            k = (num - 1) // m
            cnt += k
            m = num // (k + 1)
        return cnt

总结

相比上周好多了,继续努力

经验分享 程序员 微信小程序 职场和发展