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].

直接说思路, 切块的数量最少是1, 因为整体排序一定能达到最终有序, 我们要做的其实就是在这一整块的基础之上尽可能多的找下刀的点进行`补刀`。那什么样的位置可以`补刀`呢?我们把例子中的数组排好序然后原数组跟排序后的数组一对照,答案就出来了。

original:  [1, 0, 2, 3, 4]

sorted:    [0, 1, 2, 3, 4]

很明显,1、0之后可以切一刀, 因为这两个元素排完序后仍然在我们`切`出的这个范围之内。这样就很好解决了, sliding window拿来套用就行了, 只不过这次我们要把两个数组zip起来进行slide, 只要两个窗口内的元素一样就可以下刀了。

以下为代码实现(Rust):


use std::collections::HashSet;

impl Solution {
    pub fn max_chunks_to_sorted(arr: Vec<i32>) -> i32 {
        let mut sorted = arr.clone();
        sorted.sort();
        // 原数组元素set
        let mut o_set: HashSet<i32> = HashSet::new();
        // 排序后数组元素set
        let mut s_set: HashSet<i32> = HashSet::new();
        let mut count = 0;
        for (o, s) in arr.into_iter().zip(sorted) {
            o_set.insert(o);
            s_set.insert(s);
            // 如果两个set中的元素相同,则证明这一部分可以作为单独的一个chunk, 计数加1, 然后清空两个set中的元素, 继续向下进行
            if o_set == s_set {
                count += 1;
                o_set.clear();
                s_set.clear();
            }
        }
        count
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值