【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;
    }
}

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