(leetcode题解)Shortest Unsorted Continuous Subarray

Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.

You need to find the shortest such subarray and output its length.

Example 1:

Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

 

Note:

  1. Then length of the input array is in range [1, 10,000].
  2. The input array may contain duplicates, so ascending order here means <=.

题意是在一个给定数组寻找违反升序排列的子数组的长度。

解题思路先将其赋给一个临时数组,并对数组排序,记录两个数组中第一个不同和最后一个不同的位置,两者距离只差加1就是子数组的长度。

int findUnsortedSubarray(vector<int>& nums) {
        if(nums.empty())
            return 0;
        vector<int> temp=nums;
        vector<int> res;
        sort(temp.begin(),temp.end());
        for(int i=0;i<temp.size();i++)
        {
            if(nums[i]!=temp[i])
            {
                res.push_back(i);
            }
        }
        if(res.empty())
            return 0;
        return res[res.size()-1]-res[0]+1;
    }

 

posted on 2017-06-11 21:21  kiplove  阅读(259)  评论(0编辑  收藏  举报

导航