LeetCode 题解工作台

数组元素的最小非零乘积

给你一个正整数 p 。你有一个下标从 1 开始的数组 nums ,这个数组包含范围 [1, 2 p - 1] 内所有整数的二进制形式(两端都 包含 )。你可以进行以下操作 任意 次: 从 nums 中选择两个元素 x 和 y 。 选择 x 中的一位与 y 对应位置的位交换。对应位置指的是两个整数 相…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们注意到,每一次操作,并不会改变元素的和,而在元素和不变的情况下,要想使得乘积最小,应该尽可能最大化元素的差值。 由于最大的元素为 $2^p - 1$,无论与哪个元素交换,都不会使得差值变大,因此我们不需要考虑与最大元素交换的情况。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数 p 。你有一个下标从 1 开始的数组 nums ,这个数组包含范围 [1, 2p - 1] 内所有整数的二进制形式(两端都 包含)。你可以进行以下操作 任意 次:

  • nums 中选择两个元素 x 和 y  。
  • 选择 x 中的一位与 y 对应位置的位交换。对应位置指的是两个整数 相同位置 的二进制位。

比方说,如果 x = 1101 且 y = 0011 ,交换右边数起第 2 位后,我们得到 x = 1111 和 y = 0001 。

请你算出进行以上操作 任意次 以后,nums 能得到的 最小非零 乘积。将乘积对 109 + 7 取余 后返回。

注意:答案应为取余 之前 的最小值。

 

示例 1:

输入:p = 1
输出:1
解释:nums = [1] 。
只有一个元素,所以乘积为该元素。

示例 2:

输入:p = 2
输出:6
解释:nums = [01, 10, 11] 。
所有交换要么使乘积变为 0 ,要么乘积与初始乘积相同。
所以,数组乘积 1 * 2 * 3 = 6 已经是最小值。

示例 3:

输入:p = 3
输出:1512
解释:nums = [001, 010, 011, 100, 101, 110, 111]
- 第一次操作中,我们交换第二个和第五个元素最左边的数位。
    - 结果数组为 [001, 110, 011, 100, 001, 110, 111] 。
- 第二次操作中,我们交换第三个和第四个元素中间的数位。
    - 结果数组为 [001, 110, 001, 110, 001, 110, 111] 。
数组乘积 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512 是最小乘积。

 

提示:

  • 1 <= p <= 60
lightbulb

解题思路

方法一:贪心 + 快速幂

我们注意到,每一次操作,并不会改变元素的和,而在元素和不变的情况下,要想使得乘积最小,应该尽可能最大化元素的差值。

由于最大的元素为 2p12^p - 1,无论与哪个元素交换,都不会使得差值变大,因此我们不需要考虑与最大元素交换的情况。

对于其它的 [1,..2p2][1,..2^p-2] 的元素,我们依次将首尾元素两两配对,即 xx2p1x2^p-1-x 进行配置,那么经过若干次操作过后,每一对元素都变成了 (1,2p2)(1, 2^p-2),那么最终的乘积为 (2p1)×(2p2)2p11(2^p-1) \times (2^p-2)^{2^{p-1}-1}

时间复杂度 O(p)O(p),空间复杂度 O(1)O(1)

1
2
3
4
5
class Solution:
    def minNonZeroProduct(self, p: int) -> int:
        mod = 10**9 + 7
        return (2**p - 1) * pow(2**p - 2, 2 ** (p - 1) - 1, mod) % mod
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Tests understanding of greedy strategies and invariant validation.

  • question_mark

    Evaluates knowledge of bit manipulation and modulo arithmetic.

  • question_mark

    Assesses the ability to optimize mathematical problems through simple operations.

warning

常见陷阱

外企场景
  • error

    Failing to maintain the invariant and inadvertently setting the product to zero.

  • error

    Mismanaging bit-swapping operations, leading to incorrect results.

  • error

    Not applying modulo arithmetic, resulting in overflow or incorrect answers.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allowing a larger range for `p`.

  • arrow_right_alt

    Testing with arrays that contain duplicates or a more diverse range of binary numbers.

  • arrow_right_alt

    Modifying the operation to include swaps between non-adjacent elements.

help

常见问题

外企场景

数组元素的最小非零乘积题解:贪心·invariant | LeetCode #1969 中等