84 views
Проверка массива на монотонность (Is Monotonic) Условие: Реализуйте функцию isMonotonic(numbers), которая принимает массив чисел и определяет, является ли он монотонным — то есть либо полностью не убывающим (каждый следующий элемент больше или равен предыдущему), либо полностью не возрастающим (каждый следующий элемент меньше или равен предыдущему). Входные данные: numbers — массив целых или вещественных чисел, длина от 0 до 10^5. Выходные данные: true, если массив монотонный (не убывает ИЛИ не возрастает на всём протяжении), иначе false. Ограничения: - 0 ≤ numbers.length ≤ 10^5 - -10^9 ≤ numbers[i] ≤ 10^9 - Массивы длиной 0 или 1 считаются монотонными по умолчанию. Код для реализации: ```python # Доступно без импорта: json, sys, io def is_monotonic(numbers): # TODO: напишите решение здесь return True ```
Asked at
AI answer
def is_monotonic(numbers):
non_decreasing = True
non_increasing = True
for i in range(1, len(numbers)):
if numbers[i] < numbers[i - 1]:
non_decreasing = False
if numbers[i] > numbers[i - 1]:
non_increasing = False
if not non_decreasing and not non_increasing:
return False
return True
Both possible directions are checked at the same time. Equal adjacent elements do not violate either direction, so arrays of length 0 or 1 also return True. The time complexity is O(n), and the additional space complexity is O(1).
Also asked at getmatch agency
- Why did you leave your previous job?
- What types of data are there in Python?
- Tell us about your work experience.
- A user uploads a video and selects the desired processing, which he wants to get. The service accepts the video, applies the necessary processing, and outputs the final result. By processing, we can understand, for example, the following: make the video black and white, flip it, speed it up N times, etc. It is important that the user can monitor the progress of the processing. Load: 10,000 videos per minute
- What frameworks have you worked with?
Similar questions
- Given an integer array `nums` sorted in non-decreasing order, return an array of the squares of each number, also sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121] Constraints: - 1 <= nums.length <= [phone] <= nums[i] <= 104 - `nums` is sorted in non-decreasing order.
- Return the index of an element in a sorted array that has been cyclically shifted, or -1 if the element is not found. For example, given the array [4, 5, 6, 7, 0, 1, 2], searching for 0 should return 4, while searching for 3 should return -1.
- Write code to print each number and its count in an array if the number appears more than once.
- Are strings isomorphic?
- Write a function that takes a list of numbers as input and returns a new list containing only the unique elements of the original list, maintaining their order.