其他分享
首页 > 其他分享> > leetcode-Algorithms-581|最短无序连续子数组

leetcode-Algorithms-581|最短无序连续子数组

作者:互联网

原题

给你一个整数数组 nums ,你需要找出一个 连续子数组 ,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。

请你找出符合题意的 最短 子数组,并输出它的长度。

 

示例 1:

输入:nums = [2,6,4,8,10,9,15]
输出:5
解释:你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
示例 2:

输入:nums = [1,2,3,4]
输出:0
示例 3:

输入:nums = [1]
输出:0
 

提示:

1 <= nums.length <= 104
-105 <= nums[i] <= 105
 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

将排序后的数组与原始数组进行比较,分别找出不一样的最左和最右的索引

代码

class Solution {
    public int findUnsortedSubarray(int[] nums) {
     int[]tmp=new int[nums.length];
        for(int i=0;i<nums.length;i++)tmp[i]=nums[i];
        Arrays.sort(nums);
        int i=0,j=nums.length-1;
        while(i<nums.length){
            if(nums[i]!=tmp[i]){
                break;
            }else{
                i++;
            }
        }
        while(j>-1){
            if(nums[j]!=tmp[j]){
                break;
            }else{
                j--;
            }
        }
        return j>i? j-i+1:0;
    }
}

标签:nums,int,581,示例,Algorithms,数组,升序,排序,leetcode
来源: https://blog.csdn.net/qq_38173650/article/details/119358221