zoukankan      html  css  js  c++  java
  • [LeetCode] 769. Max Chunks To Make Sorted

    Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into some number of "chunks" (partitions), and individually sort each chunk.  After concatenating them, the result equals the sorted array.

    What is the most number of chunks we could have made?

    Example 1:

    Input: arr = [4,3,2,1,0]
    Output: 1
    Explanation:
    Splitting into two or more chunks will not return the required result.
    For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.
    

    Example 2:

    Input: arr = [1,0,2,3,4]
    Output: 4
    Explanation:
    We can split into two chunks, such as [1, 0], [2, 3, 4].
    However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
    

    Note:

    • arr will have length in range [1, 10].
    • arr[i] will be a permutation of [0, 1, ..., arr.length - 1].

    最多能完成排序的块。

    数组arr是[0, 1, ..., arr.length - 1]的一种排列,我们将这个数组分割成几个“块”,并将这些块分别进行排序。之后再连接起来,使得连接的结果和按升序排序后的原数组相同。

    我们最多能将数组分成多少块?

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/max-chunks-to-make-sorted
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    这道题我直接给出discussion最高票答案。这道题算是比较考验观察能力吧,目前还没有遇到别的题有跟这道题有类似思路的。由于题目给的元素是从0开始,所以如果数组是有序的话,数字 arr[i] 会和下标 i 正好相同。题目问的是能最多分割成几个部分,那么我们要找的就是每个分割部分里的最大元素,如果我们能找到某个区间里的最大元素arr[i] == 这一段里面最大的下标 i,就说明可以分段了。这样的分段方法最后会得到的最多的块。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public int maxChunksToSorted(int[] arr) {
     3         int count = 0;
     4         int max = arr[0];
     5         for (int i = 0; i < arr.length; i++) {
     6             max = Math.max(max, arr[i]);
     7             if (max == i) {
     8                 count++;
     9             }
    10         }
    11         return count;
    12     }
    13 }

    LeetCode 题目总结

  • 相关阅读:
    Error: listen EADDRINUSE :::3000
    getElementsByTagName
    AWTK是如何保证代码质量的
    $("div:has(p)") 选取含有元素的元素
    $("div:contains('我')选取含有文本"我"的元素
    不怕从头再来,他通过种植黄连发家致富
    生活所迫下的创业,靠空气清新机的一笔订单他就赚了100万元
    她在创业过程中,将员工转变为合伙人
    数据开源工具:Hadoop为企业带来什么?
    团队中的 Node.js 具体实践
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14615560.html
Copyright © 2011-2022 走看看