Monotonic Array

Prompt

Write a function that takes in an array of integers and returns a boolean representing whether the array is monotonic.
An array is said to be monotonic if its elements, from left to right, are entirely nonincreasing or entirely non-decreasing.

Sample Input

arrag = [-1, -5, -10, -8020}

Sample Output

true

Solution 1

import java.util.*;

class Program {
	// O(n) time | O(1) space 
  public static boolean isMonotonic(int[] array) {
    // Write your code here.
    var isNonDecreasing = true;//B
    var isNonIncreasing = true;//C
    for (int i = 1; i < array.length ;i++ ) {
    	if (array[i] > array[i - 1]) {
    		isNonIncreasing = false;
    	}

    	if (array[i] < array[i - 1]) {
    		isNonDecreasing = false;
    	}
    }
    return isNonDecreasing || isNonIncreasing;  //A
  }
}

# 1A

有两种结果,这种思路会很简洁

# 1B

isNonDecresing 命名包含了相等的情况

# 1C

Solution 2

import java.util.*;

class Program {
	// O(n) time | O(1) space
  public static boolean isMonotonic(int[] array) {
		if (array.length <= 2) return true;//A
    // Write your code here.
    var direction = array[1] - array[0];
    for (int i = 2; i < array.length ;i++ ) {
    	if (direction == 0) {//B
    		direction = array[i] - array[i - 1];
    		continue;
    	}
    	if (breakDirection(direction, array, i)) return false;//C
    }a
    return true;
  }

  public static boolean breakDirection(int direction, int[] array, int i) {
  	int difference = array[i] - array[i - 1];
  	if (direction > 0) return difference < 0;
  	return difference > 0; 
  }
}

# 2A

数组的题目 要考虑数组的长短

# 2B

见识的太少了 不要想当然

# 2C

把if的wet语句,用这种方式写进辅助函数里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值