leetcode 896单调数列

题目:
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

Note:

1 <= A.length <= 50000
-100000 <= A[i] <= 100000
题解:
python 一行解法
return not {cmp(i,j) for i,j in zip(A,A[1:])}>={1,-1}

这里面用到了集合,python的集合具有以下特性:无序性,确定性,互异性
确定性:给定任何一个元素,该元素属于或者不属于这个集合,二者必居其一,不允许有模棱两可的情况出现
互异性:一个集合中,任何两个元素都认为是不相同的,即每个元素只能出现一次
无序性:一个集合中,每个元素的地位都是相同的,元素之间是无序的(当然数学上面可以定义序关系,使得元素之间可以按照序关系进行排序,呃,偏题了,不好意思)
python 集合的运算操作:
假设有两个实数集x,y
**>>> x = set(‘spam’)
>>> y = set([‘h’,‘a’,‘m’])
>>> x, y
(set([‘a’, ‘p’, ‘s’, ‘m’]), set([‘a’, ‘h’, ‘m’]))
集合的运算操作演示如下
>>> x & y # 交集
set([‘a’, ‘m’])

>>> x | y # 并集
set([‘a’, ‘p’, ‘s’, ‘h’, ‘m’])

**>>> x - y # 差集
set([‘p’, ‘s’])
>>> x^y #对称差集,即项在x或y中,但不会同时出现在两个集合中,其结果可表示为x|y-x&y
set([‘h’, ‘s’, ‘p’])

然后就是关系运算了
s.issubset(t)
s <= t
测试是否 s 中的每一个元素都在 t 中

s.issuperset(t)
s >= t
测试是否 t 中的每一个元素都在 s 中

猜你喜欢

转载自blog.csdn.net/weixin_44482648/article/details/86517567