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
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active"]
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; }
[/restab]
[/restabs]
6.Test
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active" ]
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)); } }
[/restab]
[/restabs]
Comments | NOTHING