原题链接在这里: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 <= jA[i] <= A[j].  An array A is monotone decreasing if for all i <= jA[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. 1 <= A.length <= 50000
  2. -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;
}
}

最新文章

  1. ThreadPool.QueueUserWorkItem的用法
  2. Linux下chkconfig命令详解 这个简单明了啊
  3. MySQL_关于用嵌套表计算的可以不用 20161205
  4. Luke 6:43-45
  5. hihoCoder 1014trie树(字典树)
  6. C++—动态内存管理之深入探究new和delete
  7. Nodejs.安装.非源码方式安装Node.js (Centos)
  8. [转]【安卓笔记】AsyncTask源码剖析
  9. Oracle查询所有表的字段明细
  10. linux磁盘IO读写性能优化
  11. [DIV+CSS] set the screen capture Part 1 (div截取屏幕)
  12. (Zero XOR Subset)-less-线性基
  13. [Web]flask-excel实现excel文件下载的前后端实现
  14. Scaleform 中的 3D视角相关研究
  15. LG2521 [HAOI2011]防线修建
  16. 团队作业(二):ASB
  17. CentOS环境变量配置并生效
  18. API的HTTP Status Code
  19. linux下安装jenkins
  20. RocketMQ 使用及常见问题

热门文章

  1. 编译和安装openssl
  2. python解决自动化测试静态页面加载慢的情况
  3. 【C++】如何使用GCC生成动态库和静态库
  4. Java 8——接口中个的默认方法和静态方法
  5. 浅析libuv源码-node事件轮询解析(4)
  6. 虚拟机Ubuntu18.04 root下 连接 windows 中 winScp
  7. WebUploader 上传文件 错误总结
  8. [個人紀錄] git 疑難排解
  9. C#下载csv代码总结
  10. PIESDK二次开发基础视频