前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-581-Shortest Unsorted Continuous Subarray

leetcode-581-Shortest Unsorted Continuous Subarray

作者头像
chenjx85
发布2019-03-14 10:19:50
3730
发布2019-03-14 10:19:50
举报

题目描述:

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:

代码语言:javascript
复制
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: 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 <=

要完成的函数:

int findUnsortedSubarray(vector<int>& nums) 

说明:

1、这道题给了一个vector,要求找到一个子数组,当把这个子数组升序排列之后,整个数组也就升序排列了。要求找到那个最短的子数组。

2、我们可以先把数组升序排列,看一下数组中元素的最终位置,当某个元素未排序之前没有在它的最终位置,那意味着这个元素必须被排列过,也就是会在子数组中。

题目给的例子,[2,6,4,8,10,9,15],升序排列之后为[2,4,6,8,9,10,15],我们可以看到4/6/9/10都没有在最终位置上,这四个数必须被排列,元素8在最终位置上,但是由于整个子数组被升序排列,所以8也要包含在其中。

所以其实我们只需要找到——从左边数起第一个没有在最终位置的元素,和,从右边数起第一个没有在最终位置的元素。他们中间的元素必须被重新排列。

所以,代码如下:

代码语言:javascript
复制
    int findUnsortedSubarray(vector<int>& nums) 
    {
        vector<int>nums1=nums;
        sort(nums.begin(),nums.end());
        int i,j;
        for(i=0;i<nums.size();i++)
        {
            if(nums[i]!=nums1[i])
                break;
        }
        if(i==nums.size())//如果数组原先就是升序排列的
            return 0;
        for(j=nums.size()-1;j>=0;j--)
        {
            if(nums[j]!=nums1[j])
                break;
        }
        return j-i+1;
    }

上述代码实测55ms,beats 24.74% of cpp submissions。

3、改进:

这道题还有其他方法可以做,笔者最开始也是用的更加直接的方法……但是后来发现这个算法过程有点复杂……

等之后想到了再来更新吧。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档