896. Monotonic Array

LeetCode easy original: C# #array #csharp #easy #leetcode
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.

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

예제:

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

Output: true

C# 해법

매칭됨/원본
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++ 해법

자동 초안, 제출 전 검토
#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 해법

매칭됨/원본
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 해법

매칭됨/원본
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.

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

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

😎

Vacancies for this task

활성 채용 with overlapping task tags are 표시됨.

전체 채용
아직 활성 채용이 없습니다.