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:
- Then length of the input array is in range [1, 10,000].
- The input array may contain duplicates, so ascending order here means <=.
題目標簽:Array
題目給了我們一個nums array, 讓我們找出一個最短的無序連續子數組,當我們把這個子數組排序之后,整個array就已經是排序的了。
要找到這個子數組的范圍,先要了解這個范圍的beg 和 end 是如何定義的。
來看這個例子:1 3 5 7 2 4 5 6
a. 當我們找到第一個違反ascending 排序的數字 2的時候,我們不能是僅僅把beg 標記為2的前面一個數字7,而是要一直往前,找到一個合適的位置,找到在最前面位置的比2大的數字,這里是3。
b. 同樣的,為了找end, 那么我們要從7的后面開始找,一直找到一個最后面位置的比7小的數字,這里是6。
這樣的話,范圍就是3到6 是我們要找的子數組。把3到6排序完了之后,整個array 就已經是排序的了。
這里我們可以發現,2是min, 7是max,所以我們可以分兩個方向來分別尋找beg 和end。
從右到左(綠色),維護更新min 和 beg;
從左到右(紅色),維護更新max 和 end。
Java Solution:
Runtime beats 89.16%
完成日期:10/15/2017
關鍵詞:Array
關鍵點:分別以兩個方向來找到beg 和 end
1 class Solution 2 { 3 public int findUnsortedSubarray(int[] nums) 4 { 5 int n = nums.length; 6 int beg = -1; 7 int end = -2; // end is -2 is because it works if the array is already in ascending order 8 int min = nums[n-1]; // from right to left 9 int max = nums[0]; // from left to right 10 11 for(int i=0; i<n; i++) 12 { 13 max = Math.max(max, nums[i]); 14 min = Math.min(min, nums[n-1-i]); 15 16 if(nums[i] < max) 17 end = i; 18 if(nums[n-1-i] > min) 19 beg = n-1-i; 20 } 21 22 return end - beg + 1; // if array is already in ascending order, -2 - (-1) + 1 = 0 23 } 24 }
參考資料:
https://discuss.leetcode.com/topic/89282/java-o-n-time-o-1-space
LeetCode 題目列表 - LeetCode Questions List