Skip to content

Latest commit

 

History

History
33 lines (27 loc) · 877 Bytes

【Day 6】768. 最多能完成排序的块 II.md

File metadata and controls

33 lines (27 loc) · 877 Bytes

思路

没得思路,我没看懂😥,下面是官方题解。

代码

class Solution {
    public int maxChunksToSorted(int[] arr) {
        Map<Integer, Integer> count = new HashMap();
        int ans = 0, nonzero = 0;

        int[] expect = arr.clone();
        Arrays.sort(expect);

        for (int i = 0; i < arr.length; ++i) {
            int x = arr[i], y = expect[i];

            count.put(x, count.getOrDefault(x, 0) + 1);
            if (count.get(x) == 0) nonzero--;
            if (count.get(x) == 1) nonzero++;

            count.put(y, count.getOrDefault(y, 0) - 1);
            if (count.get(y) == -1) nonzero++;
            if (count.get(y) == 0) nonzero--;

            if (nonzero == 0) ans++;
        }

        return ans;
    }
}

复杂度分析

  • 时间复杂度:O(NlogN),其中N为arr的长度。
  • 空间复杂度:O(N)。