[力扣c++实现] 581. 最短无序连续子数组

581. 最短无序连续子数组

给你一个整数数组 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/problems/shortest-unsorted-continuous-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

1.c++

#include <iostream>
#include <vector>
#include <algorithm>

class Solution {
public:
    int findUnsortedSubarray(std::vector<int>& nums) {
        std::vector<std::pair<int,int>> value2Seq;
        int size = (int)nums.size();
        for (int i = 0 ; i < size; ++i)
        {
            value2Seq.push_back({nums[i],i});
        }
        
        std::vector<std::pair<int,int>> v2SwithSort = value2Seq;
        std::stable_sort(v2SwithSort.begin(),v2SwithSort.end(),[&](const auto p1,const auto p2){
            return p1.first < p2.first;
        });

        //找到不同的交集
        int i = 0;
        std::vector<std::pair<int,int>> subSeqs;
        while (i < size)
        {
            int start = -1;
            int end = -1;
            while (i < size && v2SwithSort[i] == value2Seq[i])
            {
                ++i;
            }

            start = i;

            while (i < size && v2SwithSort[i] != value2Seq[i])
            {
                ++i;
            }

            if (start == i)//so important,why?
                break;
            end = i;
            subSeqs.push_back({start,end});
        }
        
        if (subSeqs.size() < 1)
            return 0;
        int start = subSeqs[0].first;
        int end = subSeqs[(int)subSeqs.size() - 1].second;
        return end - start;
    }
};

int main()
{
    Solution slu;
    std::vector<int> nums = {2,6,4,8,10,9,15};
    std::cout << slu.findUnsortedSubarray(nums) << std::endl;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值