leetcode-581-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 <=

 

要完成的函数:

int findUnsortedSubarray(vector<int>& nums) 

说明:

1、这道题给了一个vector,要求找到一个子数组,当把这个子数组升序排列之后,整个数组也就升序排列了。要求找到那个最短的子数组。

2、我们可以先把数组升序排列,看一下数组中元素的最终位置,当某个元素未排序之前没有在它的最终位置,那意味着这个元素必须被排列过,也就是会在子数组中。

题目给的例子,[2,6,4,8,10,9,15],升序排列之后为[2,4,6,8,9,10,15],我们可以看到4/6/9/10都没有在最终位置上,这四个数必须被排列,元素8在最终位置上,但是由于整个子数组被升序排列,所以8也要包含在其中。

所以其实我们只需要找到——从左边数起第一个没有在最终位置的元素,和,从右边数起第一个没有在最终位置的元素。他们中间的元素必须被重新排列。

所以,代码如下:

    int findUnsortedSubarray(vector<int>& nums) 
    {
        vector<int>nums1=nums;
        sort(nums.begin(),nums.end());
        int i,j;
        for(i=0;i<nums.size();i++)
        {
            if(nums[i]!=nums1[i])
                break;
        }
        if(i==nums.size())//如果数组原先就是升序排列的
            return 0;
        for(j=nums.size()-1;j>=0;j--)
        {
            if(nums[j]!=nums1[j])
                break;
        }
        return j-i+1;
    }

上述代码实测55ms,beats 24.74% of cpp submissions。

3、改进:

这道题还有其他方法可以做,笔者最开始也是用的更加直接的方法……但是后来发现这个算法过程有点复杂……

等之后想到了再来更新吧。

猜你喜欢

转载自www.cnblogs.com/king-3/p/8992385.html