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 class Solution {
 2 public:
 3     int findUnsortedSubarray(vector<int>& nums) {
 4 
 5         auto tmp = nums;
 6         
 7         int n = nums.size();
 8         
 9         sort(nums.begin(), nums.end());
10         
11         int i = 0;
12         for(; i < n; ++i)
13         {
14             if(tmp[i] != nums[i])
15                 break;
16         }
17         int j = n - 1;
18         for(; j >= 0; --j)
19         {
20             if(tmp[j] != nums[j])
21                 break;
22         }
23         return j - i + 1 > 0 ? j - i + 1 : 0;//注意不需重排的
24     }
25 };

明天来看看大神的解答 :)

posted @ 2018-03-26 22:30  还是说得清点吧  阅读(102)  评论(0编辑  收藏  举报