LeetCode 题解工作台

最大化数组的伟大值

给你一个下标从 0 开始的整数数组 nums 。你需要将 nums 重新排列成一个新的数组 perm 。 定义 nums 的 伟大值 为满足 0 且 perm[i] > nums[i] 的下标数目。 请你返回重新排列 nums 后的 最大 伟大值。 示例 1: 输入: nums = [1,3,5,2…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 双·指针·invariant

bolt

答案摘要

我们可以先将数组 进行排序。 接下来定义一个指针 ,初始时指向数组 的第一个元素。然后遍历数组 ,对于遍历到的每个元素 ,如果 大于 ,则将指针 向右移动一位。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的整数数组 nums 。你需要将 nums 重新排列成一个新的数组 perm 。

定义 nums 的 伟大值 为满足 0 <= i < nums.length 且 perm[i] > nums[i] 的下标数目。

请你返回重新排列 nums 后的 最大 伟大值。

 

示例 1:

输入:nums = [1,3,5,2,1,3,1]
输出:4
解释:一个最优安排方案为 perm = [2,5,1,3,3,1,1] 。
在下标为 0, 1, 3 和 4 处,都有 perm[i] > nums[i] 。因此我们返回 4 。

示例 2:

输入:nums = [1,2,3,4]
输出:3
解释:最优排列为 [2,3,4,1] 。
在下标为 0, 1 和 2 处,都有 perm[i] > nums[i] 。因此我们返回 3 。

 

提示:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109
lightbulb

解题思路

方法一:贪心

我们可以先将数组 numsnums 进行排序。

接下来定义一个指针 ii,初始时指向数组 numsnums 的第一个元素。然后遍历数组 numsnums,对于遍历到的每个元素 xx,如果 xx 大于 nums[i]nums[i],则将指针 ii 向右移动一位。

最后返回指针 ii 的值即可。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 为数组 numsnums 的长度。

1
2
3
4
5
6
7
8
class Solution:
    def maximizeGreatness(self, nums: List[int]) -> int:
        nums.sort()
        i = 0
        for x in nums:
            i += x > nums[i]
        return i
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Consider sorting nums before attempting greedy matches.

  • question_mark

    Think about maintaining a pointer invariant to count successful greatness increments.

  • question_mark

    Watch for repeated numbers affecting the greedy scan outcome.

warning

常见陷阱

外企场景
  • error

    Failing to sort nums leads to suboptimal matching and lower greatness.

  • error

    Advancing pointers incorrectly can skip potential matches, reducing the result.

  • error

    Ignoring duplicates can inflate or undercount greatness incorrectly.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Maximize greatness when only a subset of indices can be permuted.

  • arrow_right_alt

    Compute maximum greatness with additional constraints like fixed positions for certain elements.

  • arrow_right_alt

    Determine maximum greatness under a circular array matching constraint.

help

常见问题

外企场景

最大化数组的伟大值题解:双·指针·invariant | LeetCode #2592 中等