做一个网站完整的网页,网站后台更新 前台看不到,实训网站建设的心得总结,小天才电话手表网站题目
给你一个整数数组 nums #xff0c;你需要找出一个 连续子数组 #xff0c;如果对这个子数组进行升序排序#xff0c;那么整个数组都会变为升序排序。
请你找出符合题意的 最短 子数组#xff0c;并输出它的长度。
示例 1#xff1a;
输入#xff1a;nums [2,6…题目
给你一个整数数组 nums 你需要找出一个 连续子数组 如果对这个子数组进行升序排序那么整个数组都会变为升序排序。
请你找出符合题意的 最短 子数组并输出它的长度。
示例 1
输入nums [2,6,4,8,10,9,15]
输出5
解释你只需要对 [6, 4, 8, 10, 9] 进行升序排序那么整个表都会变为升序排序。示例 2
输入nums [1,2,3,4]
输出0示例 3
输入nums [1]
输出0提示
1 nums.length 10^4-10^5 nums[i] 10^5 解答
源代码
class Solution {public int findUnsortedSubarray(int[] nums) {if (isSorted(nums)) {return 0;}int[] numsSorted new int[nums.length];System.arraycopy(nums, 0, numsSorted, 0, nums.length);Arrays.sort(numsSorted);int left 0;while (nums[left] numsSorted[left]) {left;}int right nums.length - 1;while (nums[right] numsSorted[right]) {right--;}return right - left 1;}public boolean isSorted(int[] nums) {for (int i 1; i nums.length; i) {if (nums[i] nums[i - 1]) {return false;}}return true;}
}
总结
既然这个数组有一部分元素进行升序排序后整个数组都会变成升序排列那么最后得到的升序排列数组和一开始的原数组相比只有中间连续的一部分不同。那么我们将原数组复制一份把复制得到的数组进行排序然后对比元素得到不同部分的左右边界以得到这个子数组的长度。