# @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是将两个数组按照对应位置合并成一个由元组组成的列表,两个数组长度不一致时 # 返回的长度是短的序列的长度, 另一个是all.all是用于判断可迭代对象的所有元素不为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))
Leetcode练习<八> 将最短子序列升序排列,使整个序列满足升序排列
最新推荐文章于 2023-10-14 23:50:04 发布