896. Monotonic Array
O texto da tarefa é traduzido do russo para o idioma selecionado. O código permanece sem alterações.
array является монотонным, если он либо монотонно возрастает, либо монотонно убывает. array nums является монотонно возрастающим, если для всех i <= j, nums[i] <= nums[j]. array nums является монотонно убывающим, если для всех i <= j, nums[i] >= nums[j]. Если задан inteiro array nums, return true, если данный array монотонный, или false в противном случае.
Exemplo:
Input: nums = [1,2,2,3]
Output: true
C# solução
correspondente/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++ solução
rascunho automático, revisar antes de enviar#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 solução
correspondente/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 solução
correspondente/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;
};
Algorithm
Определить два флага: increasing и decreasing.
Пройтись по arrayу: Если текущий element больше следующего, установить increasing в false. Если текущий element меньше следующего, установить decreasing в false.
Вернуть true, если хотя бы один из флагов true, иначе вернуть false.
😎
Vacancies for this task
vagas ativas with overlapping task tags are mostradas.
Ainda não há vagas ativas.