美文网首页
581. Shortest Unsorted Continuou

581. Shortest Unsorted Continuou

作者: larrymusk | 来源:发表于2017-11-24 21:04 被阅读0次

[2, 6, 4, 8, 10, 9, 15]
max 记录当前数字之前的最大值 比如4之前的[2,6] 是6,一直找到最后一个满足以上条件的坐标,标记为end
min记录当前数字之后的最小值, 比如10之后的[9,15]最小值是9,

当前值如果比max小,暂定为破坏递增排序数组的最后一个数字end
[2, 6, 4, 8, 10, 9, 15] 就是4->9
当前值如果大于min ,暂定为浦破坏递增的第一个数start
10->6

所以start = 1 end=5 ,return 5-1+1 = 5,[6,4,8,10,9]

#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)

int findUnsortedSubarray(int* nums, int numsSize) {
            int max = nums[0];  
            int min = nums[numsSize - 1];  
            int beg = -1;  
            int end = -2;  
            for (int i = 1; i < numsSize; i++) {  
                max = max(max, nums[i]);  
                min = min(min, nums[numsSize - i - 1]);  
                if (max > nums[i]) {  
                    end = i;  
                }  
                if (min < nums[numsSize - i - 1]) {  
                    beg = numsSize - i - 1;  
                }  
            }  
            return end - beg + 1;  
}  

相关文章

网友评论

      本文标题:581. Shortest Unsorted Continuou

      本文链接:https://www.haomeiwen.com/subject/zuafbxtx.html