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 };
  • 相关阅读:
    如何结合后台数据库 启动vue项目
    nodejs卸载安装
    mysql安装过程
    VUE-cli脚手架
    css伪类
    element中遇到的表格问题总结
    小程序折叠面板的功能
    vue学习中遇到的onchange、push、splice、forEach方法使用
    vscode好用的扩展及常用的快捷键
    Flutter之SliverAppBar
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/7647233.html
Copyright © 2011-2022 走看看