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.
题目给了我们一个nums array, 让我们找出一个最短的无序连续子数组
-
int n = nums.length; int[] temp = new int[n]; for (int i = 0; i < n; i++) temp[i] = nums[i]; Arrays.sort(temp); int start = 0; while (start < n && nums[start] == temp[start]) start++; int end = n - 1; while (end > start && nums[end] == temp[end]) end--; return end - start + 1; class Solution { public: int findUnsortedSubarray(vector<int>& nums) { vector<int> nums2 = nums; sort(nums.begin(),nums.end()); int begin = -1; int end = -2; for(int i = 0;i < nums.size(); i++) { if(nums[i] != nums2[i]) { if(begin == -1) begin = i; end = i; } } return end - begin + 1; } };