Leetcode 3011. Find if Array Can Be Sorted

1. 解题思路

这一题挺简单的,就是一个分组进行排序考察,我们将相邻且bit set相同的元素划归到同一组,然后进行排序,然后依次看各个组之间是不是都满足有序关系即可。

2. 代码实现

给出python代码实现如下:

class Solution:
    def canSortArray(self, nums: List[int]) -> bool:
        n = len(nums)
        
        def count_digit(num):
            return Counter(bin(num)[2:])["1"]
        
        idx = 0
        pre_max = -1
        while idx < n:
            elems = []
            d = count_digit(nums[idx])
            while idx < n and count_digit(nums[idx]) == d:
                elems.append(nums[idx])
                idx += 1
            elems = sorted(elems)
            if elems[0] < pre_max:
                return False
            pre_max = elems[-1]
        return True

提交代码评测得到:耗时143ms,占用内存16.7MB。

相关推荐

  1. Leetcode 3011. Find if Array Can Be Sorted

    2024-01-23 01:20:01       32 阅读
  2. Leetcode 3016. Minimum Number of Pushes to Type Word II

    2024-01-23 01:20:01       36 阅读
  3. Leetcode 3012. Minimize Length of Array Using Operations

    2024-01-23 01:20:01       36 阅读
  4. Leetcode 3021. Alice and Bob Playing Flower Game

    2024-01-23 01:20:01       38 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-23 01:20:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-23 01:20:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-23 01:20:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-23 01:20:01       20 阅读

热门阅读

  1. docker下安装rabbitmq

    2024-01-23 01:20:01       37 阅读
  2. fastapi框架

    2024-01-23 01:20:01       34 阅读
  3. C# Cad 文字信息导入导出(八)

    2024-01-23 01:20:01       43 阅读
  4. ansible模块讲解

    2024-01-23 01:20:01       34 阅读
  5. Day32- 贪心算法part06

    2024-01-23 01:20:01       39 阅读
  6. RHCE第三次作业

    2024-01-23 01:20:01       33 阅读
  7. QReadWriteLock的学习

    2024-01-23 01:20:01       32 阅读
  8. 【vue-cli详细介绍】

    2024-01-23 01:20:01       35 阅读
  9. HttpServletRequest HttpEntity StringEntity 区别

    2024-01-23 01:20:01       32 阅读
  10. 【AI理论知识】EM算法

    2024-01-23 01:20:01       42 阅读