辣雞劉的Leetcode之旅4 (Weekly Contest 100)【單調序列,】

896. Monotonic Array

題目描述:
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
意思很簡單,判斷是否單調;
舉例:

Example 1:

Input: [1,2,2,3]
Output: true
Example 2:

Input: [6,5,4,4]
Output: true
Example 3:

Input: [1,3,2]
Output: false
Example 4:

Input: [1,2,4,5]
Output: true
Example 5:

Input: [1,1,1]
Output: true

我的辦法很笨重:

class Solution:
    def isMonotonic(self, A):
        """
        :type A: List[int]
        :rtype: bool
        """
        if len(A)==1:return True
        else:
            if A[0]<A[1]:return self.increase(A)
            elif A[0]>A[1]: return  self.decrease(A)
            elif A[0]==A[1] and len(A)==2:
                return True
            else:
                if A[1]<A[len(A)-1]:return self.increase(A)
                else: return  self.decrease(A)

    def increase(self,A):
        index = []
        list_len = len(A)
        for i in range(list_len - 1):
            if A[i] <= A[i + 1]:
                index.append('True')
            else:
                index.append('False')
        if 'False' in index:
            return False
        else:
            return True

    def decrease(self,A):
        index = []
        list_len = len(A)
        for i in range(list_len - 1):
            if A[i] >= A[i + 1]:
                   index.append('True')
            else:
                index.append('False')
        if 'False' in index:
            return False
        else:
            return True

s=Solution()
s.isMonotonic([-5,-5,-5,-5,-2,-2,-2,-1,-1,-1,0])

我的思路笨拙,但是很簡單。再看看人家的:

def isMonotonic(self, A):
        return not {cmp(i, j) for i, j in zip(A, A[1:])} >= {1, -1}
上面用到的思想和函數:
cmp(x,y) 函數用於比較2個對象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。

我滴媽………..
官方參考答案:

 return (all(A[i] <= A[i+1] for i in xrange(len(A) - 1)) or
                all(A[i] >= A[i+1] for i in xrange(len(A) - 1)))

函數:

all() 函數用於判斷給定的可迭代參數 iterable 中的所有元素是否都爲 TRUE,如果是返回 True,否則返回 False。
元素除了是 0、空、FALSE 外都算 TRUE。
但是注意:
>>> all([])             # 空列表
True
>>> all(())             # 空元組
True
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章