LeetCode-Easy-Java-Shortest Unsorted Continuous Subarray

来源:互联网 发布:压菠菜的软件 编辑:程序博客网 时间:2024/06/06 06:38

最短无序连续子数组

题目描述:

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.

Example 1:

Input: [2, 6, 4, 8, 10, 9, 15]Output: 5Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

Note:

  1. Then length of the input array is in range [1, 10,000].
  2. The input array may contain duplicates, so ascending order here means <=
就是给定一个数组,去找它最短的无序子数组,若这个子数组是有序递增的,则整个数组都是有序递增的。
最初思路:定义两个变量start与end,寻找第一个无序的位置更新start,和最后一个无序的位置更新end,最后返回end-start+1。start,end的更新条件为每遇到一个逆序对,start为较大数的坐标,end为较小数的坐标。
然而,第一次实现的时候,认为找到了第一个start就不应该变了,没有考虑后面会有更小的数,可能会移到start之前。例如[3,3,2,1,4]第一个start为坐标1,实际上再往后判断start应该为坐标0,因此start也是需要实时更新的。
正确代码为:

int findUnsortedSubarray(int[] nums) {        int n = nums.length, start = -1, end = -2;        int min = nums[n - 1], max = nums[0];        for (int i = 1; i < n; ++i) {            max = maxValue(max, nums[i]);            min = minValue(min, nums[n - 1 - i]);            if (max > nums[i]) end = i;            if (min < nums[n - 1 - i]) start = n - 1 - i;        }        return end - start + 1;    }int maxValue(int a, int b){if(a>=b){return a;}else {return b;}}int minValue(int a, int b){if(a<b){return a;}else{return b;}}



解释:max初始值为数组第一位的值,min初始值为数组最后一位的值。循环判断时分别从头和从尾判断,遇到比max大的则说明序列递增,end不变,遇到比max小的,说明这个max应该往回移,更新end值;遇到比min小的说明序列递增,start不变,遇到比min大的说明这个min应该往前移,更新start。

由于当时第一个思路一直没有解决好,所有有了思路2:先将数组复制一份,然后对数组排序,找到第一个不相等的坐标和最后一个不相等的坐标,相减即可。

正确代码如下:

public int findUnsortedSubarray(int[] nums) {        if(nums.length==1){            return 0;        }        int[] numsTemp=nums.clone();        Arrays.sort(nums);        int start=-1;        int end=-1;               for(int i=0;i<nums.length;i++){            if(nums[i]!=numsTemp[i]){                if(start==-1){                    start=i;                }                end=i+1;            }        }                return end-start;    }

这里需要注意的是,如果采用这样的方式复制数组是无效的,

int[] numsTemp = nums;

这样复制的数组与nums指向的是同一个数组对象,因此Arrays.sort(nums)也对numsTemp有作用,循环判断会发现它们的元素是一模一样的。

因此数组的复制要用nums.clone()。

此题更加详细的解释可以参考这篇博客,感觉比我写的好~

http://www.cnblogs.com/grandyang/p/6876457.html

更多算法内容 关注 FunctionY csdn博客

阅读全文
1 0
原创粉丝点击