題目解析
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.
找到最短的連續(xù)子數(shù)組,滿足子數(shù)組有序后整個(gè)數(shù)組有序。
算法思路
1)i、j,i用于找子數(shù)組起始位置,j遍歷整個(gè)數(shù)組并且找子數(shù)組結(jié)束位置;
2)minSub、maxSub為子數(shù)組中的最大最小值,每當(dāng)i、j移動(dòng)都需要判斷兩個(gè)變量并賦值;
3)結(jié)果子數(shù)組需要滿足的條件,子數(shù)組中最小值minSum>=nums[i-1],子數(shù)組中的最大值maxSum<=nums[j+1];
4)在該循環(huán)里j不斷向后遍歷,但每當(dāng)minSub的值改變需要重新判斷i的位置;
5)跳出循環(huán)的條件,j遍歷到數(shù)組結(jié)尾,同時(shí)滿足minSum>=nums[i-1]。
ps:這個(gè)循環(huán)條件調(diào)試了好久啊??!