LeetCode 题解工作台

检查整数及其两倍数是否存在

给你一个整数数组 arr ,请你检查是否存在两个整数 N 和 M ,满足 N 是 M 的两倍(即, N = 2 * M )。 更正式地,检查是否存在两个下标 i 和 j 满足: i != j 0 arr[i] == 2 * arr[j] 示例 1: 输入: arr = [10,2,5,3] 输出: …

category

5

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们定义一个哈希表 ,用于记录访问过的元素。 遍历数组 ,对于每个元素 ,如果 的两倍或者 的一半在哈希表 中,那么返回 `true`。否则将 加入哈希表 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 arr,请你检查是否存在两个整数 NM,满足 N 是 M 的两倍(即,N = 2 * M)。

更正式地,检查是否存在两个下标 ij 满足:

  • i != j
  • 0 <= i, j < arr.length
  • arr[i] == 2 * arr[j]

 

示例 1:

输入:arr = [10,2,5,3]
输出:true
解释:N = 10 是 M = 5 的两倍,即 10 = 2 * 5 。

示例 2:

输入:arr = [7,1,14,11]
输出:true
解释:N = 14 是 M = 7 的两倍,即 14 = 2 * 7 

示例 3:

输入:arr = [3,1,7,11]
输出:false
解释:在该情况下不存在 N 和 M 满足 N = 2 * M 。

 

提示:

  • 2 <= arr.length <= 500
  • -10^3 <= arr[i] <= 10^3
lightbulb

解题思路

方法一:哈希表

我们定义一个哈希表 ss,用于记录访问过的元素。

遍历数组 arrarr,对于每个元素 xx,如果 xx 的两倍或者 xx 的一半在哈希表 ss 中,那么返回 true。否则将 xx 加入哈希表 ss

若遍历结束后没有找到满足条件的元素,返回 false

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

1
2
3
4
5
6
7
8
9
class Solution:
    def checkIfExist(self, arr: List[int]) -> bool:
        s = set()
        for x in arr:
            if x * 2 in s or (x % 2 == 0 and x // 2 in s):
                return True
            s.add(x)
        return False
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    They mention storing values from indices [0, i - 1] while scanning, which points directly to a seen-set solution.

  • question_mark

    They ask how to avoid comparing every pair, which usually means replace brute force with O(1) membership checks.

  • question_mark

    They emphasize different indices i and j, which is a clue to check before inserting the current value into the hash set.

warning

常见陷阱

外企场景
  • error

    Checking only one direction, such as whether 2 * x was seen, misses pairs where the larger number appears earlier.

  • error

    Forgetting the even-number guard before checking x / 2 can create incorrect matches for odd values.

  • error

    Adding the current number to the set before lookup can falsely treat one element as both sides of the pair, especially around 0.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Sort the array and use binary search for each value, but the logic becomes less direct than the hash lookup pattern.

  • arrow_right_alt

    Use a frequency map if you also want to reason explicitly about duplicates like two zeroes.

  • arrow_right_alt

    Return the actual index pair instead of a boolean, which requires storing positions rather than only seen values.

help

常见问题

外企场景

检查整数及其两倍数是否存在题解:数组·哈希·扫描 | LeetCode #1346 简单