896. Monotonic Array
leetcode easy
#array#csharp#easy#leetcode
Task
Массив является монотонным, если он либо монотонно возрастает, либо монотонно убывает. Массив nums является монотонно возрастающим, если для всех i <= j, nums[i] <= nums[j]. Массив nums является монотонно убывающим, если для всех i <= j, nums[i] >= nums[j]. Если задан целочисленный массив nums, верните true, если данный массив монотонный, или false в противном случае.
Пример:
Input: nums = [1,2,2,3]
Output: true
C# solution
matched/originalpublic class Solution {
public bool IsMonotonic(int[] nums) {
bool increasing = true, decreasing = true;
for (int i = 1; i < nums.Length; i++) {
if (nums[i] > nums[i - 1]) decreasing = false;
if (nums[i] < nums[i - 1]) increasing = false;
}
return increasing || decreasing;
}C++ solution
auto-draft, review before submit#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public bool IsMonotonic(vector<int>& nums) {
bool increasing = true, decreasing = true;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] > nums[i - 1]) decreasing = false;
if (nums[i] < nums[i - 1]) increasing = false;
}
return increasing || decreasing;
}Java solution
matched/originalclass Solution {
public boolean isMonotonic(int[] nums) {
boolean increasing = true, decreasing = true;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) decreasing = false;
if (nums[i] < nums[i - 1]) increasing = false;
}
return increasing || decreasing;
}
}JavaScript solution
matched/originalvar isMonotonic = function(nums) {
let increasing = true, decreasing = true;
for (let i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) decreasing = false;
if (nums[i] < nums[i - 1]) increasing = false;
}
return increasing || decreasing;
};Explanation
Algorithm
Определить два флага: increasing и decreasing.
Пройтись по массиву: Если текущий элемент больше следующего, установить increasing в false. Если текущий элемент меньше следующего, установить decreasing в false.
Вернуть true, если хотя бы один из флагов true, иначе вернуть false.
😎