要求: 检验一个数组是否是单调的
输入:
复制代码
1
2[-1, -5, -10, -1100, -900, -1101, -1102, -9001]
输出:
复制代码
1
2False
Solution 1:
先确定一个方向,然后遍历这个数组,看看是否破坏之前的方向。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29def isMonotonic(array): up_down = 0; if len(array)<=2: return True direction = array[1]-array[0] for _ in range(2,len(array)): if direction == 0: #update direction direction = array[_]-array[_-1] continue if if_break(direction,current = array[_],previous = array[_-1]): return False return True def if_break(direction,previous,current): if (current-previous)*direction < 0: return True else: return False test_arr = [-1, -5, -10, -1100, -900, -1101, -1102, -9001] print(isMonotonic(array = test_arr))
Time: O(n) Space: O(1)
Solution 2:
更简单的方法,假设不增不减是成立的,看是否有情况破坏这个条件。
不增不减意味着单调。
不增 是 单调
不减 是 单调
如果同时不满足这两个条件,那么就不是单调。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18def isMonotonic(array): # 假设不增不减,看是否有情况破坏这个条件 isNotIncreasing = True isNotDecreasing = True for _ in range(1,len(array)): if array[_]>array[_-1]: isNotIncreasing = False if array[_]<array[_-1]: isNotDecreasing = False return isNotDecreasing or isNotIncreasing test_arr = [-1, -5, -10, -1100, -900, -1101, -1102, -9001] print(isMonotonic(array = test_arr))
Time: O(n) Space: O(1)
最后
以上就是顺心汽车最近收集整理的关于Python-is Monotonic-数组-检验数组是否单调Solution 1:Solution 2:的全部内容,更多相关Python-is内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复