跳转至

判断一个数组是否可以变为有序⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

分组循环

class Solution {
public:
    bool canSortArray(vector<int>& nums) {
        int n = nums.size();
        for (int i = 0; i < n; ) {
            int start = i;
            int ones = __builtin_popcount(nums[i++]);
            while (i < n && __builtin_popcount(nums[i]) == ones) i++;
            sort(nums.begin() + start, nums.begin() + i);
        }
        return is_sorted(nums.begin(), nums.end());
    }
};