当前位置:网站首页>shortest-unsorted-continuous-subarray
shortest-unsorted-continuous-subarray
2022-07-25 09:26:00 【scwMason】
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 <=.
先将原序列进行排序,然后跟原序列比较,看这个序列前后从哪个开始与排序好的序列开始不同,然后相减:
比如上面的例子中
2, 6, 4, 8, 10, 9, 15
排序以后
2,4,6,8,9,10,15
所以前面开始从4开始也就是第2位不同,后面开始10不同,也就是第6位,所以6-2+1=5
所以:
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
nums2=sorted(nums)
right=0
left=-1
for index in range(0,len(nums)):
if nums[index]!=nums2[index]:
left=index
for index in range(len(nums)-1,-1,-1):
if nums[index]!=nums2[index]:
right=index
return left-right+1之前因为不清楚sorted这个可以返回排序的序列的方法,所以用了两个深拷贝(copy.deepcopy)导致运行速度偏慢。
边栏推荐
猜你喜欢

CCF 201604-2 Tetris

ROS distributed operation -- launch file starts nodes on multiple machines

canal实现mysql数据同步

TM1638 LED数码显示模块ARDUINO驱动代码

ROS分布式操作--launch文件启动多个机器上的节点

概率机器人学习笔记第二章

【近万字干货】别让你的简历配不上你的才华——手把手教你制作最适合你的简历

Mlx90640 infrared thermal imaging sensor temperature measurement module development notes (III)

Internal structure of SOC chip

小程序调起微信支付
随机推荐
Excel导入导出源码分析
字符串切片的用法
字典树的使用
概率机器人学习笔记第二章
TM1637带秒点四位LED显示器模块ARDUINO驱动程序
Introduction to arm GIC
小程序H5获取手机号方案
小程序企业发放红包功能
Data viewing and parameter modification of multi-channel vibrating wire, temperature and analog sensing signal acquisition instrument
salt常见问题
JSP details
腾讯云之错误[100007] this env is not enable anonymous login
阿里MQTT物联网平台“云产品流转”实战——两片ESP32通过物联网平台实现远程互操作
ADC introduction
cookie and session
Summary of most consistency problems
SSM整合(简单的图书管理系统来整合SSM)
TM1638 LED数码显示模块ARDUINO驱动代码
js利用requestAnimationFrame实时检测当前动画的FPS帧率
vant问题记录