TypechoJoeTheme

IT技术分享

统计

[LeetCode 581] Shortest Unsorted Continuous Subarray [Java] [Runtime : 22MS]

2017-09-19
/
0 评论
/
701 阅读
/
正在检测是否收录...
09/19

1. Description

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.

2. Runtime Distribution

3. Submission Details

4. Example

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.

5. Code

public int findUnsortedSubarray(int[] nums) {

    if (nums == null || nums.length == 0) {
        return 0;
    }
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
    int right = 0;
    int left = nums.length - 1;

    for (int i = 0; i < nums.length; i++) {
        if (nums[i] >= max) {
            max = nums[i];
            continue;
        }
        right = i;
    }
    for (int j = nums.length - 1; j >= 0; j--) {
        if (nums[j] <= min) {
            min = nums[j];
            continue;
        }
        left = j;
    }
    return left >= right ? 0 : right - left + 1;
}

6.Test

package com.leetcode;

public class LeetCode0581 {

    public int findUnsortedSubarray(int[] nums) {

        if (nums == null || nums.length == 0) {
            return 0;
        }
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        int right = 0;
        int left = nums.length - 1;

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] >= max) {
                max = nums[i];
                continue;
            }
            right = i;
        }
        for (int j = nums.length - 1; j >= 0; j--) {
            if (nums[j] <= min) {
                min = nums[j];
                continue;
            }
            left = j;
        }
        return left >= right ? 0 : right - left + 1;
    }

    public static void main(String[] args) {
        LeetCode0581 leetcode = new LeetCode0581();
        int[] nums = new int[] { 2, 6, 4, 8, 10, 9, 15 };
        System.out.println(leetcode.findUnsortedSubarray(nums));
    }
}
Array
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/901/(转载时请注明本文出处及文章链接)