896. Monotonic Array

LeetCode easy original: C# #array #csharp #easy #leetcode
Der Aufgabentext wird für die gewählte Sprache aus dem Russischen übersetzt. Code bleibt unverändert.

Array является монотонным, если он либо монотонно возрастает, либо монотонно убывает. Array nums является монотонно возрастающим, если для всех i <= j, nums[i] <= nums[j]. Array nums является монотонно убывающим, если для всех i <= j, nums[i] >= nums[j]. Если задан Ganzzahl Array nums, return true, если данный Array монотонный, или false в противном случае.

Beispiel:

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

Output: true

C# Lösung

zugeordnet/original
public 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++ Lösung

Auto-Entwurf, vor dem Einreichen prüfen
#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 Lösung

zugeordnet/original
class 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 Lösung

zugeordnet/original
var 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;
};

Algorithm

Определить два флага: increasing и decreasing.

Пройтись по Arrayу: Если текущий element больше следующего, установить increasing в false. Если текущий element меньше следующего, установить decreasing в false.

Вернуть true, если хотя бы один из флагов true, иначе вернуть false.

😎

Stellen zu dieser Aufgabe

aktive Stellen with overlapping task tags are angezeigt.

Alle Stellen
Es gibt noch keine aktiven Stellen.