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.
Example 1:
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:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.

Subscribe to see which companies asked this question.

代码

func findUnsortedSubarray(_ nums: [Int]) -> Int {
    var arr = nums
    arr.sort()
    var start = 0
    var end = nums.count - 1
    while start < nums.count && nums[start] == arr[start] {
        start += 1
    }
    
    while end > start && nums[end] == arr[end] {
        end -= 1
    }
    return end - start + 1
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,501评论 0 23
  • 我在大学里的阅读量并不算少,大学毕业藏书300多册,但我仍觉得自己的阅读量不够,每次经过书店,看到店里陈设的书籍,...
    少羡阅读 4,381评论 1 11
  • 今天的花洒 淋在阳光上 倦懒的阴影 伸了长长的懒腰 黑色的线条被无限拉长 随着目光 一段在天空明亮的尽头 一段在早...
    心种阅读 1,148评论 0 0
  • 今日新得 1.来自张潇雨 商业史学习的时候,四个“不要”三个“要”。 第一,不要把商业当物理学。观察现象——提出假...
    Pheeb阅读 1,342评论 0 0

友情链接更多精彩内容