LeetCode 面试题 16.16. 部分排序

文章目录

一、题目

  给定一个整数数组,编写一个函数,找出索引m和n,只要将索引区间m,n的元素排好序,整个数组就是有序的。注意:n-m尽量最小,也就是说,找出符合条件的最短序列。函数返回值为m,n,若不存在这样的m和n(例如整个数组是有序的),请返回-1,-1

示例:

输入: 1,2,4,7,10,11,7,12,6,7,16,18,19
输出: 3,9

提示:

  • 0 <= len(array) <= 1000000

  点击此处跳转题目

二、C# 题解

  笨蛋方法就是,先排序,然后一个一个比较。

csharp 复制代码
public class Solution {
    public int[] SubSort(int[] array) {
        int[] sorted = new int[array.Length], ans = { -1, -1 };
        Array.Copy(array, sorted, array.Length);
        Array.Sort(sorted);
        for (var i = 0; i < array.Length; i++) {
            if (ans[0] == -1 && array[i] != sorted[i]) ans[0] = i;
            if (ans[1] == -1 && array[^(i + 1)] != sorted[^(i + 1)]) ans[1] = array.Length - i - 1;
        }
        return ans;
    }
}
  • 时间:204 ms,击败 40.00% 使用 C# 的用户
  • 内存:54.22 MB,击败 40.00% 使用 C# 的用户

  一次遍历也可以实现,原理是:乱序的左端 > 右边的最小值,乱序的右端 < 左边的最大值。

  从左向右遍历,寻找乱序的右端;从右向左遍历,寻找乱序的左端。

⟵ ⟵ ⟵ ⟵ ⟵ ⏞ m i n = 6 { 1 2 4 ⋮ 7 ‾ 10 11 7 12 6 7 ‾ ⋮ 16 18 19 } ⏟ m a x = 12 ⟶ ⟶ ⟶ ⟶ ⟶ \begin{array}{l} \longleftarrow \hspace{1em} \longleftarrow \hspace{1em} \longleftarrow \hspace{1em} \longleftarrow \hspace{1em} \longleftarrow \hspace{0.8em} \overbrace{\hspace{26.5em}}^{min=6}\\ \{\hspace{0.78em} 1 \hspace{2.2em} 2 \hspace{2.25em} 4 \hspace{1.4em} \vdots \hspace{1.4em} \underline{\bold{7}} \hspace{2.1em} 10 \hspace{2.25em} 11 \hspace{2.25em} 7 \hspace{2.1em} 12 \hspace{2.25em} 6 \hspace{2.4em} \underline{\bold{7}} \hspace{1.4em} \vdots \hspace{1.4em} 16 \hspace{2.25em} 18 \hspace{2.25em} 19 \} \\ \hspace{1.2em} \underbrace{\hspace{24.8em} }_{max=12} \hspace{1em} \longrightarrow \hspace{1em} \longrightarrow \hspace{1em} \longrightarrow \hspace{1em} \longrightarrow \hspace{1em} \longrightarrow\\ \end{array} ⟵⟵⟵⟵⟵ min=6{124⋮7101171267⋮161819}max=12 ⟶⟶⟶⟶⟶

  • 时间:184 ms,击败 100.00% 使用 C# 的用户
  • 内存:53.18 MB,击败 80.00% 使用 C# 的用户
相关推荐
wanzehongsheng2 分钟前
零碳产业园光伏园区光伏电站追踪对比固定:发电增益技术边界分析
算法·光伏发电·光伏·零碳园区·太阳能追光·低碳环保·追踪电站
KobeSacre27 分钟前
CyclicBarrier 源码
java·jvm·算法
手写码匠27 分钟前
注意力机制全家桶:从 Multi-Head 到 GQA 再到 Flash Attention 的手写实现
人工智能·深度学习·算法·aigc
Lucky_Turtle1 小时前
【论文写作】PDF图片不清晰,打印生成PDF空白大,PDF字体嵌入
开发语言·pdf·c#
学究天人1 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷3.2)
线性代数·算法·机器学习·数学建模·动态规划·抽象代数·拓扑学
Yang_jie_031 小时前
笔记:数据结构(链队列的相关判断条件)
数据结构·笔记
tkevinjd1 小时前
力扣322-零钱兑换
算法·leetcode·动态规划
大鱼>1 小时前
AI+资产监控:农业设施智能监控系统
人工智能·深度学习·算法·机器学习
AI科技星2 小时前
乖乖数学·全域超复数统一场论:五大核心门槛与全套标准定量数据
人工智能·python·算法·金融·全域数学
Frostnova丶2 小时前
(13)LeetCode 53. 最大子数组和
算法·leetcode·职场和发展