leetcode刷题记录1051-1060 python版

前言

继续leetcode刷题生涯
这里记录的都是笔者觉得有点意思的做法
参考了好几位大佬的题解,感谢各位大佬

1051. 高度检查器

class Solution:
    def heightChecker(self, heights: List[int]) -> int:
        h_sort = sorted(heights)
        res = 0
        for i in range(len(heights)):
            if h_sort[i] != heights[i]:
                res += 1
        return res

1052. 爱生气的书店老板

class Solution:
    def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
        n = len(customers)
        res = 0
        for i in range(n):
            if grumpy[i] == 0:
                res += customers[i]
                customers[i] = 0
        tmp = sum(customers[:X])
        res2 = tmp
        for i in range(1, n-X+1):
            tmp = tmp + customers[i+X-1] - customers[i-1]
            res2 = max(res2, tmp)
        return res + res2

1053. 交换一次的先前排列

class Solution:
    def prevPermOpt1(self, A: List[int]) -> List[int]:
        n = len(A)
        for i in range(n-1, 0, -1):
            if A[i-1] > A[i]:
                for j in range(n-1, i-1, -1):
                    if A[j] < A[i-1] and A[j] != A[j-1]:
                        A[i-1],A[j] = A[j],A[i-1]
                        return A
        return A

1054. 距离相等的条形码

class Solution:
    def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
        import collections
        counter = collections.Counter(barcodes)
        sortedCounter = sorted(counter, key=lambda k:0 - counter[k])
        barcodes = []
        for i in sortedCounter:
            barcodes += [i] * counter[i]
        res = [None for _ in range(len(barcodes))]
        res[::2] = barcodes[:len(res[::2])]
        res[1::2] = barcodes[len(res[::2]):]
        return res

猜你喜欢

转载自blog.csdn.net/weixin_44604541/article/details/108961537