581. Shortest Unsorted Continuous Subarray

weekly contest 32的第一题。这题我一开始就想着把每个子串都拿出来sort一遍再放回去,跟sort完的对比一下。但是复杂度太高(O(n2)), TLE了(但是用熟了System.arraycopy(nums, 0, temp, 0, nums.length);这个方法。。)。
如下:

Approach 1: BRUTE FORCE(TIME LIMIT EXCEEDED)

    public int findUnsortedSubarray(int[] nums) {
        if (nums == null || nums.length == 0) return 0;

        int sorted[] = new int[nums.length];
        System.arraycopy(nums, 0, sorted, 0, nums.length);

        Arrays.sort(sorted);
        if (Arrays.equals(sorted, nums)) return 0;

        int minLen = nums.length;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                int temp[] = new int[nums.length];
                System.arraycopy(nums, 0, temp, 0, nums.length);
                Arrays.sort(temp, i, j + 1);
                if (Arrays.equals(sorted, temp)) {
                    minLen = Math.min(j + 1 - i, minLen);
                    break;
                }
            }
        }
        return minLen;
    }

Approach 2: Compare the sorted parts

从首位开始跟sort过的array相比。Time : O(nlogn)。

    public int findUnsortedSubarray(int[] nums) {
        int [] temp = new int[nums.length];
        System.arraycopy(nums,0 , temp , 0 , nums.length);
        Arrays.sort(temp);
        int start = 0 , end = nums.length -1 ;
        while (start< nums.length && temp[start] == nums[start] ){
            start ++ ;
        }
        while (end> start && temp[end] == nums[end]){
            end -- ;
        }
        return end + 1 - start;
    }

还看到有一种O(n)的解法,现在脑子晕了不想看了。

ref:
https://discuss.leetcode.com/topic/89282/java-o-n-time-o-1-space
https://discuss.leetcode.com/category/741/shortest-unsorted-continuous-subarray
Java拷贝数组的几种方法:
http://www.cnblogs.com/jjdcxy/p/5870524.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,793评论 0 33
  • 题目描述 Given an integer array, you need to find onecontinuo...
    龙之力量V阅读 349评论 1 1
  • 7月19日,今天舒怀从青岛姑姑家回来了我问他怎么回来了,儿子说妈妈我想你了你也不来看看我,所以我只有回来看看你啊。...
    指间的阳光923802阅读 275评论 0 0
  • JavaScript 可以通过不同的方式来输出数据: 使用 window.alert() 弹出警告框。使用 doc...
    余继莲阅读 1,946评论 0 0
  • 1、苹果酵素可以减肥 苹果酵素可以减肥,这是人们食用它的最大好处之一,因这种天然酵素中有大量的酸性成分,它们进入人...
    云狂ing阅读 432评论 0 0