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. Return the shortest such subarray and output its length.
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.
To find the shortest subarray that, when sorted, results in the entire array being sorted, we can follow these steps:
import java.util.Arrays;
public class Solution {
public int findUnsortedSubarray(int[] nums) {
int n = nums.length;
int[] sortedNums = Arrays.copyOf(nums, n);
Arrays.sort(sortedNums);
int start = 0;
while (start < n && nums[start] == sortedNums[start]) {
start++;
}
int end = n - 1;
while (end >= 0 && nums[end] == sortedNums[end]) {
end--;
}
return (start < end) ? (end - start + 1) : 0;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {2, 6, 4, 8, 10, 9, 15};
System.out.println(sol.findUnsortedSubarray(nums)); // Output: 5
}
}
O(n log n)
, where n
is the length of the array.O(n)
.Thus, the overall time complexity is O(n log n)
due to the sorting step.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?