题目链接:https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/
题目大意:
略.
分析:
如果排序区间为 [L, R], 那么 nums[L] 一定大于区间内的最小值,而 nums[R] 一定大于区间内的最大值, 按照这个特性分别求出左右端点即可.
代码如下:
1 const int inf = 0x7fffffff; 2 3 class Solution { 4 public: 5 int findUnsortedSubarray(vector<int>& nums) { 6 int L = 0, R = -1; 7 int N = nums.size(); 8 int maxNum = -inf, minNum = inf; 9 10 for(int i = 0; i < N; ++i) { 11 if(maxNum <= nums[i]) maxNum = nums[i]; 12 else R = i; 13 } 14 15 for(int i = N - 1; i >= 0; --i) { 16 if(minNum >= nums[i]) minNum = nums[i]; 17 else L = i; 18 } 19 20 return R - L + 1; 21 } 22 };
原文地址:https://www.cnblogs.com/zaq19970105/p/11475160.html
时间: 2024-09-27 04:34:38