Shortest Unsorted Continuous Subarray

来源:互联网 发布:python 爬虫框架 编辑:程序博客网 时间:2024/05/21 19:31

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.


  1. int n = nums.length;  
  2.    int[] temp = new int[n];  
  3.    for (int i = 0; i < n; i++) temp[i] = nums[i];  
  4.    Arrays.sort(temp);  
  5.      
  6.    int start = 0;  
  7.    while (start < n  && nums[start] == temp[start]) start++;  
  8.      
  9.    int end = n - 1;  
  10.    while (end > start  && nums[end] == temp[end]) end--;  
  11.      
  12.    return end - start + 1;  
  1. class Solution {  
  2. public:  
  3.     int findUnsortedSubarray(vector<int>& nums) {  
  4.         vector<int> nums2 = nums;  
  5.         sort(nums.begin(),nums.end());  
  6.         int begin = -1;  
  7.         int end = -2;  
  8.         for(int i = 0;i < nums.size(); i++)  
  9.         {  
  10.             if(nums[i] != nums2[i])   
  11.             {  
  12.                 if(begin == -1)  
  13.                     begin = i;  
  14.                 end = i;  
  15.             }  
  16.         }  
  17.         return end - begin + 1;  
  18.     }  
  19. };