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.

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:这个是我能想到,数组排序的方式

package leetcode;

import org.junit.Test;
import java.util.Arrays;

/**
 * @author zhangyu
 * @version V1.0
 * @ClassName: ShortestUnsortedContinuousSubarray
 * @Description: TOTO
 * @date 2018/12/6 14:39
 **/


public class ShortestUnsortedContinuousSubarray {
   /* @Test
    public void fun() {
        int[] nums = {1, 3, 2, 4, 5};
        int number = shortestUnsortedContinuousSubarray(nums);
        System.out.println(number);
    }*/

    private int shortestUnsortedContinuousSubarray(int[] nums) {
        int[] newNums = Arrays.copyOfRange(nums, 0, nums.length);
        Arrays.sort(newNums);
        int number = 0;
        int i = 0;
        int j = nums.length - 1;
        while (i < j) {
            if (nums[i] == newNums[i]) {
                i++;
            } else if (nums[j] == newNums[j]) {
                j--;
            } else if (i == j) {
                return 0;
            } else {
                return j - i + 1;
            }
        }
        return number;
    }
}

时间复杂度:O(n.logn)

空间复杂度:O(n)

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/84855501