757. 最短无序数组

757. 最短无序数组

中文 English

给定一个整数数组,求出无序整数的最短子序列的长度。如果一组整数既不递减也不递增,则称为无序。[提示:开始检查它是否递增/递减并返回0,否则检查是否存在无序的三元组。如果是,则返回3,否则返回0]

样例

样例 1:

输入:[1,2,3,4,5,6]
输出:0
解释:一个递增数组。

样例 2:

输入:[1,2,1,2]
输出:3
解释:[1,2,1]
class Solution:
    """
    @param arr: an array of integers
    @return: the length of the shortest possible subsequence of integers that are unordered
    """
    '''
    大致思路:
    1.给出一个方法,判断是否是有序的(递增或者递减均可以)
    2.如果是有序的话,则返回0,否则返回3
    '''
    def shortestUnorderedArray(self,arr):
        if self.isSort(arr) == True or self.isSort(arr[::-1]) == True:
            return 0
        return 3


    ##只按递增来判断返回
    def isSort(self,A):
        origin = A[0]
        for i in A[1:]:
            if i<origin:
                return False
            origin = i
        return True
 

猜你喜欢

转载自www.cnblogs.com/yunxintryyoubest/p/12542342.html