脸书面试原题:单调数列
LintCode 1745
单调数列
题目描述 如果数组是单调递增或单调递减的,那么它是单调的。 如果对于所有 i <= j
,A[i] <= A[j]
,那么数组 A
是单调递增的。如果对于所有 i <= j
,A[i]> = A[j]
,那么数组 A
是单调递减的。 当给定的数组 A
是单调数组时返回 true
,否则返回 false
。 1≤A.length≤50000
- −100000≤A[i]≤100000
题目描述
i <= j
,A[i] <= A[j]
,那么数组 A
是单调递增的。如果对于所有 i <= j
,A[i]> = A[j]
,那么数组 A
是单调递减的。A
是单调数组时返回 true
,否则返回 false
。−100000≤A[i]≤100000
扫码免费做题 ↓↓↓
样例 1
输入:[1,2,2,3]
输出:true
样例 2
输入:[1,3,2]
输出:false
解题思路
先假设数组为单调递增,也为单调递减。遍历一遍数组,判断是否破坏了递增或递减的单调性。若递增或递减其中一种属性未被破坏,即始终为true,返回其中一种结果
源代码
publicclassSolution{
/**
* @param A: a array
* @return: is it monotonous
*/
publicbooleanisMonotonic(int[] A){
// Write your code here.
boolean inc = true, dec = true;
for (int i = 1; i < A.length; ++i) {
inc &= A[i - 1] <= A[i];
dec &= A[i - 1] >= A[i];
}
return inc || dec;
}
}
查看完整代码,向左滑动
点击【阅读原文】,查看领扣原题。
阅读原文 关键词
代码
题目
单调递增
思路
属性
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。