Leetcode学习笔记:#581. Shortest Unsorted Continuous Subarray

Leetcode学习笔记:#581. Shortest Unsorted Continuous Subarray

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.

实现:

public int findUnsortedSubarray(int[] nums){
	int[] snums = nums.clone();
	Arrays.sort(snums);
	int start = snums.length, end = 0;
	for(int i = 0; i < snums.length; i++){
		if(snums[i] != nums[i])){
			start = Math.min(start, i);
			end = Math.max(end, i);
		}
	}
	return (end - start >= 0? end-start + 1 : 0);

思路:
克隆一个原数组,把它排序后与原数组比较,如果位置不相等则更新start和end,类似与一个滑动的窗口不断更新其长度。

猜你喜欢

转载自blog.csdn.net/ccystewart/article/details/90176001