LeetCode 题解工作台

将每个元素替换为右侧最大元素

给你一个数组 arr ,请你将每个元素用它右边最大的元素替换,如果是最后一个元素,用 -1 替换。 完成所有替换操作后,请你返回这个数组。 示例 1: 输入: arr = [17,18,5,4,6,1] 输出: [18,6,6,6,1,-1] 解释: - 下标 0 的元素 --> 右侧最大元素是下标…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们用一个变量 记录当前位置右侧的最大值,初始时 $mx = -1$。 然后我们从右向左遍历数组,对于每个位置 ,我们记当前位置的值为 ,将当前位置的值更新为 ,然后更新 $mx = \max(mx, x)$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个数组 arr ,请你将每个元素用它右边最大的元素替换,如果是最后一个元素,用 -1 替换。

完成所有替换操作后,请你返回这个数组。

 

示例 1:

输入:arr = [17,18,5,4,6,1]
输出:[18,6,6,6,1,-1]
解释:
- 下标 0 的元素 --> 右侧最大元素是下标 1 的元素 (18)
- 下标 1 的元素 --> 右侧最大元素是下标 4 的元素 (6)
- 下标 2 的元素 --> 右侧最大元素是下标 4 的元素 (6)
- 下标 3 的元素 --> 右侧最大元素是下标 4 的元素 (6)
- 下标 4 的元素 --> 右侧最大元素是下标 5 的元素 (1)
- 下标 5 的元素 --> 右侧没有其他元素,替换为 -1

示例 2:

输入:arr = [400]
输出:[-1]
解释:下标 0 的元素右侧没有其他元素。

 

提示:

  • 1 <= arr.length <= 104
  • 1 <= arr[i] <= 105
lightbulb

解题思路

方法一:逆序遍历

我们用一个变量 mxmx 记录当前位置右侧的最大值,初始时 mx=1mx = -1

然后我们从右向左遍历数组,对于每个位置 ii,我们记当前位置的值为 xx,将当前位置的值更新为 mxmx,然后更新 mx=max(mx,x)mx = \max(mx, x)

最后返回原数组即可。

时间复杂度 O(n)O(n),其中 nn 为数组长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
class Solution:
    def replaceElements(self, arr: List[int]) -> List[int]:
        mx = -1
        for i in reversed(range(len(arr))):
            x = arr[i]
            arr[i] = mx
            mx = max(mx, x)
        return arr
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Tests understanding of array traversal and modification in-place.

  • question_mark

    Checks if the candidate is aware of optimizing both time and space complexities.

  • question_mark

    Assesses ability to handle edge cases like single-element arrays and no right elements.

warning

常见陷阱

外企场景
  • error

    Not accounting for the last element, which must be replaced with -1.

  • error

    Confusing the order of operations when updating the elements from right to left.

  • error

    Using unnecessary extra space when the problem can be solved in-place.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling arrays with only one element.

  • arrow_right_alt

    Modifying the problem to work with arrays of floating-point numbers.

  • arrow_right_alt

    Implementing the solution with additional constraints such as negative numbers.

help

常见问题

外企场景

将每个元素替换为右侧最大元素题解:数组·driven | LeetCode #1299 简单