zoukankan      html  css  js  c++  java
  • 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 <=.

    对最短的子数组做升序排序,使得整个数组都按升序排序

    C++(52ms):

     1 class Solution {
     2 public:
     3     int findUnsortedSubarray(vector<int>& nums) {
     4         vector<int> sortNums(nums.begin() , nums.end()) ;
     5         sort(sortNums.begin() , sortNums.end()); 
     6         int len = nums.size() ;
     7         int i = 0 ;
     8         int j =  len - 1 ;
     9         while(i < len && sortNums[i] == nums[i])
    10             i++ ;
    11         while(j > i && sortNums[j] == nums[j])
    12             j-- ;
    13         return j - i + 1 ;
    14     }
    15 };

    C++(39ms):

     1 class Solution {
     2 public:
     3     int findUnsortedSubarray(vector<int>& nums) {     
     4         int len = nums.size() ;
     5         vector<int> minNums(len) ;
     6         vector<int> maxNums(len) ;
     7         int Min = nums[len-1] ;
     8         for(int i = len-1 ; i >= 0 ; i--){
     9             minNums[i] = Min = min(Min , nums[i]) ;
    10         }
    11         int Max = nums[0] ;
    12         for(int i = 0 ; i < len ; i++){
    13             maxNums[i] = Max = max(Max , nums[i]) ;
    14         }
    15         int i = 0 ;
    16         int j = len - 1 ;
    17         while(i < len && nums[i] <= minNums[i])
    18             i++ ;
    19         while(j > i && nums[j] >= maxNums[j])
    20             j-- ;
    21         return j - i + 1 ;
    22     }
    23 };
  • 相关阅读:
    android 4.0 support sf mkv parser on GB.
    Android关于OutOfMemoryError的一些思考
    android devices offline
    Android 查看内存使用情况
    android模块编译,mm,mmm
    eclipse老是building workspace及自动更新问题,eclipse加速
    如何在android native编程中使用logCat
    ANDROID 静音与振动
    android中sim卡相关操作
    真机缺少com.google.android.maps.jar解决方法:
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/7647233.html
Copyright © 2011-2022 走看看