LeetCode 896. 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: nums = [1,2,2,3]
Output: true

Example 2:

Input: nums = [6,5,4,4]
Output: true

Example 3:

Input: nums = [1,3,2]
Output: false

Example 4:

Input: nums = [1,2,4,5]
Output: true

Example 5:

Input: nums = [1,1,1]
Output: true

解题想法

宣告变数,updown,若出现递增,则down = 0,出现递减up = 0,如果最终down = 0up = 0,表示无法通过验证。

Solution

var isMonotonic = function (A) {
  let up = 1;
  let down = 1;
  for (let i = 1; i < A.length; i++) {
    if (A[i] > A[i - 1]) {
      down = 0;
    } else if (A[i] < A[i - 1]) {
      up = 0;
    }
  };
  return (down || up);
};

<<:  [Day30] 建立购物车系统 - 13 & 完赛心得

>>:  谁温暖了资安部-赛後感想

简单了解VR头盔中,重要且相辅相成的Eye tracking 与Foveated Rendering技术 1

真的很初步的了解(汗,不一定是对的哈 眼球追踪技术(Eyetracking)注视点宣染技术(Fove...

[Day7] 词性标注(二)-方法介绍

一. 马可夫模型(Markov Model) 以下会简称为MM。MM是一种具有状态的随机过程,从目前...

Day21 xib传值的小教室2

接续昨天。 到到二个页面的程序码中,新增一字串变数,也在生命周期中,使此变数会等於第二页的文字格变数...

从 IT 技术面细说 Search Console 的 27 组数字 KPI (12) :网页体验 - Core Web Vitals

注:这篇不打算讲 Core Web Vitals 的介绍、以及如何去解决,因为这资讯很难靠这样一篇写...

电子商贸系列 | 善用电子商贸增加客源

电子商贸系列 | 善用电子商贸增加客源 电子商贸系列能助你了解建立网上商店的实际流程及细节,并挑选最...