begin,end必须初始化,如果整个数组是排序好的,经过for循环后,begin、end还是原始的值。
注意:end必须比begin小1,因为最终的长度是end - begin + 1,关键在于这个+1的地方
class Solution { public: int findUnsortedSubarray(vector<int>& nums) { int length = nums.size(); if(length <= 0) return 0; int max_num = nums[0],min_num = nums[length-1]; int begin = 0,end = -1; for(int i = 0;i < length;i++){ if(nums[i] > max_num) max_num = nums[i]; if(nums[length-1-i] < min_num) min_num = nums[length-1-i]; if(nums[i] < max_num) end = i; if(nums[length-1-i] > min_num) begin = length-1-i; } return end - begin + 1; } };
https://www.cnblogs.com/jimmycheng/p/7673733.html