Leetcode练习<八> 将最短子序列升序排列,使整个序列满足升序排列

# @greg 20170518
# 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.
# 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.

# 问题描述,给定一个数组,然后找到最短的一个子序列,对子序列按照升序排序之后,整个序列都会按照升序排序,返回子序列的长度
# 解题思路,将原数组与排序后的数组进行zip(操作),生成一个由元组组成的列表,对元组中的元素进行比较,相等返回True,不相等
# 返回False
# 如果全都是True,表明排序后的数组与原数组是一致的,即原数组就是一个排序好的,我们不需要再对它的任何子序列进行排序了,
# 如果不全是True,那就是要找到第一个False所在的下标(索引值),再找到最后一个False所在的下标,两个下标之间的数组就是我们要
# 排序的数组.
# len(nums) - is_same.index(False) - is_same[::-1].index(False)这样做的目的是去头去尾,去掉第一个False之前的数据
# 倒序排列之后再找到第一个False之前的数据.
# 大神写的程序,我没想出来好的办法
# 这个程序用到了两个知识点:一是zip, zip是将两个数组按照对应位置合并成一个由元组组成的列表,两个数组长度不一致时
# 返回的长度是短的序列的长度, 另一个是allall是用于判断可迭代对象的所有元素不为0,空,'false'则返回True,否则返回
# false.注意:空元组、空列表返回值为True,这里要特别注意
class Solution(object):
    def findSortedSubarray(self, nums):
        is_same = [a == b for a, b in zip(nums, sorted(nums))]
        return 0 if all(is_same) else len(nums) - is_same.index(False) - is_same[::-1].index(False)

if __name__ == '__main__':
    nums = [2, 8, 3, 5, 9, 10, 15]
    s = Solution()
    print(s.findSortedSubarray(nums))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值