1. 程式人生 > >LeetCode 581. Shortest Unsorted Continuous Subarray

LeetCode 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.

Note: Then length of the input array is in range [1, 10,000]. The input array may contain duplicates, so ascending order here means <=.

Example1

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.

二、題意分析

找到陣列中亂序的子集(連續的),使得對該子集排序後整個陣列有序,我們的任務就是找到滿足條件的最小子集。

三、解題思路

首先將陣列深度拷貝一份,然後排序,接著對比兩個陣列對應位置的元素,記錄陣列前,後第一次出現不一致的位置,它們之間的元素個數就是最短的。

程式碼實現

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        if(nums.length == 1)
            return 0;
        // 深拷貝陣列    
        int[] sortedArray = Arrays.copyOf(nums, nums.length);
        Arrays.sort(sortedArray);
        int left = 0, right = nums.length - 1;
       // 找到前面開始出現不一致的初始位置
while(left < right && nums[left] == sortedArray[left]) left++; // 找到後面開始出現不一致的初始位置 while(left < right && nums[right] == sortedArray[right]) right--; // 陣列正序 if(left == right) return 0; return right - left + 1; } }

時間、空間複雜度分析

  1. 時間複雜度

O (nlogn)

  1. 空間複雜度

O(n)

在這裡插入圖片描述