LeetCode 896. Monotonic Array
2024-09-01 10:26:27
原题链接在这里:https://leetcode.com/problems/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
Note:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000
题解:
Having a direction as d. If it is increasing, d = 1. If it is decreasing, d = -1.
When seeing a increasing, but d = -1, that means there is decreasing before, return false.
Vice Versa.
Time Complexity: O(n). n = A.length.
Space: O(1).
AC Java:
class Solution {
public boolean isMonotonic(int[] A) {
if(A == null || A.length == 0){
return true;
} int d = 0;
for(int i = 1; i<A.length; i++){
if(A[i] > A[i-1]){
if(d < 0){
return false;
} d = 1;
}else if(A[i] < A[i-1]){
if(d > 0){
return false;
} d = -1;
}
} return true;
}
}
最新文章
- ThreadPool.QueueUserWorkItem的用法
- Linux下chkconfig命令详解 这个简单明了啊
- MySQL_关于用嵌套表计算的可以不用 20161205
- Luke 6:43-45
- hihoCoder 1014trie树(字典树)
- C++—动态内存管理之深入探究new和delete
- Nodejs.安装.非源码方式安装Node.js (Centos)
- [转]【安卓笔记】AsyncTask源码剖析
- Oracle查询所有表的字段明细
- linux磁盘IO读写性能优化
- [DIV+CSS] set the screen capture Part 1 (div截取屏幕)
- (Zero XOR Subset)-less-线性基
- [Web]flask-excel实现excel文件下载的前后端实现
- Scaleform 中的 3D视角相关研究
- LG2521 [HAOI2011]防线修建
- 团队作业(二):ASB
- CentOS环境变量配置并生效
- API的HTTP Status Code
- linux下安装jenkins
- RocketMQ 使用及常见问题