NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior1 view

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.

Practice

Asked at

AI answer

Используйте два указателя: квадрат наибольшего по модулю элемента находится на одном из концов отсортированного массива. Сравнивайте квадраты крайних элементов и записывайте больший в конец результирующего массива. Сложность — O(n) по времени и O(n) по дополнительной памяти.

def sorted_squares(nums: list[int]) -> list[int]:
    n = len(nums)
    result = [0] * n
    left, right = 0, n - 1

    for i in range(n - 1, -1, -1):
        if abs(nums[left]) > abs(nums[right]):
            result[i] = nums[left] ** 2
            left += 1
        else:
            result[i] = nums[right] ** 2
            right -= 1

    return result

Например, для [-4, -1, 0, 3, 10] функция вернёт [0, 1, 9, 16, 100].

Also asked at СБЕР

Similar questions