给你一个整数数组 nums ,你需要找出一个 连续子数组 ,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
请你找出符合题意的 最短 子数组,并输出它的长度。
示例 1:
输入:nums = [2, 6, 4, 8, 10, 9, 15]
输出:5
解释:你只需要对[6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
示例 2:
输入:nums = [1, 2, 3, 4]
输出:0
示例 3:
输入:nums = [1]
输出:0
提示:
1 <= nums.length <= 104
- 105 <= nums[i] <= 105
进阶:你可以设计一个时间复杂度为 O(n) 的解决方案吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/submissions/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
思路一:排序后比较
整个数组排序,拿排序后的数组和原数组从头尾开始分别比较,从前往后找,从后往前找,两端找到不同的地方,中间的子序列就是无序的。
思路二:暴力一次遍历
我们假设确定三个序列,左、中、右三个子序列,其中左右子序列是有序的,中子序列是无序的。用双指针找出左序列和中序列,以及中序列和右序列的边界。我采用了双闭区间。如果双指针没找到边界说明有序返回0.
图解:
源代码
#include<iostream>
#include<Windows.h>
using namespace std;
// 堆排序
void Swap(int* num1, int* num2)
{
int temp = *num1;
*num1 = *num2;
*num2 = temp;
}
void AdjustDwon(int* a, int n, int root)
{
int parents = root;
int child = parents * 2 + 1;
while (child < n)
{
if (child + 1 < n && a[child + 1] > a[child])
{
child++;
}
if (a[parents] < a[child])
{
Swap