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 };
  • 相关阅读:
    Python使用SMTP模块、email模块发送邮件
    harbor搭建及使用
    ELK搭建-windows
    ELK技术栈之-Logstash详解
    【leetcode】1078. Occurrences After Bigram
    【leetcode】1073. Adding Two Negabinary Numbers
    【leetcode】1071. Greatest Common Divisor of Strings
    【leetcode】449. Serialize and Deserialize BST
    【leetcode】1039. Minimum Score Triangulation of Polygon
    【leetcode】486. Predict the Winner
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/7647233.html
Copyright © 2011-2022 走看看