space dust
Senior Member
Java:
class Solution {
public int findLengthOfShortestSubarray(int[] arr) {
int n = arr.length;
// Find the longest non-decreasing subarray from the start
int left = 0;
while (left < n - 1 && arr[left] <= arr[left + 1]) {
left++;
}
// If the entire array is already sorted
if (left == n - 1) {
return 0;
}
// Find the right boundary where the array starts to decrease
int right = n - 1;
int res = right - left; // Initial result assumes removing the middle portion
// Adjust right and try to find the shortest subarray to remove
while (right > left && (right == n - 1 || arr[right] <= arr[right + 1])) {
// Shift left pointer leftward if arr[right] is smaller than arr[left]
while (right >= 0 && left >= 0 && arr[right] < arr[left]) {
left--;
}
// Update the minimum length of the subarray to remove
res = Math.min(res, right - left - 1);
right--; // Move the right pointer leftward
}
return res;
}
}
phải áp dụng hơi nhiều skill mới ra
đi ngủ cho lành


có khi nhanh bằng merge sort .