【LeetCode】581. 最短无序连续子数组

在这里插入图片描述

想法是将数组复制一下,将复制后的数组进行排序。创建两个指针,从两头对比两个数组,直到找到不相等的位置。然后就得出了结果。

public class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int[] copy = Arrays.copyOf(nums, nums.length);
        Arrays.sort(copy);
        int i = 0;
        int j = nums.length - 1;
        while (i < nums.length && copy[i] == nums[i]) {
            i++;
        }
        while (i < j && copy[j] == nums[j]) {
            j--;
        }
        if (i < j)
            return j - i + 1;
        else return 0;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章