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

附上题目链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值