zoukankan      html  css  js  c++  java
  • (leetcode题解)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就是子数组的长度。

    int findUnsortedSubarray(vector<int>& nums) {
            if(nums.empty())
                return 0;
            vector<int> temp=nums;
            vector<int> res;
            sort(temp.begin(),temp.end());
            for(int i=0;i<temp.size();i++)
            {
                if(nums[i]!=temp[i])
                {
                    res.push_back(i);
                }
            }
            if(res.empty())
                return 0;
            return res[res.size()-1]-res[0]+1;
        }
  • 相关阅读:
    java9
    java8
    java7
    JavaScript将字符串拆分为数组
    JavaScript return false
    Java中前台往后台传多个id参数
    Easyui清除tree的选中
    jquery easyui tree的全选与反选
    android源码开发基础知识了解
    Android activity的生命周期
  • 原文地址:https://www.cnblogs.com/kiplove/p/6986416.html
Copyright © 2011-2022 走看看