LeetCode 题解工作台

至少是其他数字两倍的最大数

给你一个整数数组 nums ,其中总是存在 唯一的 一个最大整数 。 请你找出数组中的最大元素并检查它是否 至少是数组中每个其他数字的两倍 。如果是,则返回 最大元素的下标 ,否则返回 -1 。 示例 1: 输入: nums = [3,6,1,0] 输出: 1 解释: 6 是最大的整数,对于数组中的…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·排序

bolt

答案摘要

我们可以遍历数组 ,找到数组中的最大值 和第二大的值 ,如果 $x \ge 2y$,则返回 的下标,否则返回 。 我们也可以先找到数组中的最大值 ,同时找到最大值 的下标 。然后再遍历一次数组,如果发现 以外的元素 满足 $x < 2y$,则返回 。否则遍历结束后返回 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,其中总是存在 唯一的 一个最大整数 。

请你找出数组中的最大元素并检查它是否 至少是数组中每个其他数字的两倍 。如果是,则返回 最大元素的下标 ,否则返回 -1

 

示例 1:

输入:nums = [3,6,1,0]
输出:1
解释:6 是最大的整数,对于数组中的其他整数,6 至少是数组中其他元素的两倍。6 的下标是 1 ,所以返回 1 。

示例 2:

输入:nums = [1,2,3,4]
输出:-1
解释:4 没有超过 3 的两倍大,所以返回 -1 。

 

提示:

  • 2 <= nums.length <= 50
  • 0 <= nums[i] <= 100
  • nums 中的最大元素是唯一的
lightbulb

解题思路

方法一:遍历

我们可以遍历数组 numsnums,找到数组中的最大值 xx 和第二大的值 yy,如果 x2yx \ge 2y,则返回 xx 的下标,否则返回 1-1

我们也可以先找到数组中的最大值 xx,同时找到最大值 xx 的下标 kk。然后再遍历一次数组,如果发现 kk 以外的元素 yy 满足 x<2yx < 2y,则返回 1-1。否则遍历结束后返回 kk

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

1
2
3
4
5
class Solution:
    def dominantIndex(self, nums: List[int]) -> int:
        x, y = nlargest(2, nums)
        return nums.index(x) if x >= 2 * y else -1
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Ability to identify the largest element in a single scan of the array.

  • question_mark

    Understanding of how to compare array elements efficiently in two passes.

  • question_mark

    Attention to detail in ensuring that all elements are checked against the largest element.

warning

常见陷阱

外企场景
  • error

    Not verifying that the largest element is at least twice as large as all others, leading to incorrect results.

  • error

    Overcomplicating the solution with unnecessary steps or additional data structures.

  • error

    Misunderstanding the problem and incorrectly handling cases where the largest element doesn’t meet the twice condition.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider cases where the array contains only two elements.

  • arrow_right_alt

    Handle arrays with all elements being the same, except for the largest one.

  • arrow_right_alt

    What if the array contains very large or very small numbers? Ensure that edge cases are considered.

help

常见问题

外企场景

至少是其他数字两倍的最大数题解:数组·排序 | LeetCode #747 简单