leetcode-5.20[1356. 根據數字二進制下 1 的數目排序、977. 有序數組的平方、1221. 分割平衡字符串](python實現)

題目1

在這裏插入圖片描述

題解1

class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        res = []
        d = {}
        for i in arr:
            n = self.oneCount(i)
            if n not in d:
                d[n] =[]
            d[n].append(i)
        # 字典鍵值排序
        for i in sorted(d):
            # 對鍵對應的列表值排序
            res+=sorted(d[i])
        return res

    def oneCount(self, n: int) -> int:
        count = 0
        if n < 0:
            n &= 0xffffffff
        while n:
            n = n&(n-1)
            count += 1
        return count

附上題目鏈接

題目2

在這裏插入圖片描述

題解2

class Solution:
    def sortedSquares(self, A: List[int]) -> List[int]:
        # 根據絕對值排序
        A.sort(key=lambda x: abs(x))
        # 用map映射出每個元素的平方
        return list(map(lambda x:x**2,A))

附上題目鏈接

題目3

在這裏插入圖片描述

題解3

class Solution:
    def balancedStringSplit(self, s: str) -> int:
        L_count = 0
        R_count = 0
        count = 0
        for w in s:
            if w == 'R':
                if L_count == R_count:
                    count += 1
                    L_count, R_count = 0,0
                L_count += 1
            if w == 'L':
                if L_count == R_count:
                    count += 1
                    L_count, R_count = 0,0
                R_count += 1
        return count

附上題目鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章