LeetCode 题解工作台

镜面反射

有一个特殊的正方形房间,每面墙上都有一面镜子。除西南角以外,每个角落都放有一个接受器,编号为 0 , 1 ,以及 2 。 正方形房间的墙壁长度为 p ,一束激光从西南角射出,首先会与东墙相遇,入射点到接收器 0 的距离为 q 。 返回光线最先遇到的接收器的编号(保证光线最终会遇到一个接收器)。 示例…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数学·结合·几何

bolt

答案摘要

根据题意,光线在每次反射时,都会向上或向下移动 的距离,向右移动 的距离。而由于光线最后一定会遇到接收器,因此,我们需要找到一个最小的 ,使得 $k \times q$ 是 的倍数。 同时,根据 的奇偶性,我们可以确定光线最终到达了西侧还是东侧。如果 是偶数,那么光线最终到达的是西侧,否则光线最终到达的是东侧。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·结合·几何 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

有一个特殊的正方形房间,每面墙上都有一面镜子。除西南角以外,每个角落都放有一个接受器,编号为 0, 1,以及 2

正方形房间的墙壁长度为 p,一束激光从西南角射出,首先会与东墙相遇,入射点到接收器 0 的距离为 q

返回光线最先遇到的接收器的编号(保证光线最终会遇到一个接收器)。

 

示例 1:

输入:p = 2, q = 1
输出:2
解释:这条光线在第一次被反射回左边的墙时就遇到了接收器 2 。

示例 2:

输入:p = 3, q = 1
输入:1

 

提示:

  • 1 <= q <= p <= 1000
lightbulb

解题思路

方法一:数学

根据题意,光线在每次反射时,都会向上或向下移动 qq 的距离,向右移动 pp 的距离。而由于光线最后一定会遇到接收器,因此,我们需要找到一个最小的 kk,使得 k×qk \times qpp 的倍数。

同时,根据 kk 的奇偶性,我们可以确定光线最终到达了西侧还是东侧。如果 kk 是偶数,那么光线最终到达的是西侧,否则光线最终到达的是东侧。

另外,根据 k×qk \times q 除以 pp 的结果的奇偶性,我们可以确定光线最终到达的是北侧还是南侧。如果 k×qk \times qpp 的偶数倍,那么光线最终到达的是南侧,否则光线最终到达的是北侧。

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

1
2
3
4
5
6
7
8
9
class Solution:
    def mirrorReflection(self, p: int, q: int) -> int:
        g = gcd(p, q)
        p = (p // g) % 2
        q = (q // g) % 2
        if p == 1 and q == 1:
            return 1
        return 0 if p == 1 else 2
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Look for understanding of geometry and modular arithmetic.

  • question_mark

    Check if the candidate approaches the problem by first simulating the reflections.

  • question_mark

    Evaluate whether the candidate considers optimizing the solution using math-based reflection patterns.

warning

常见陷阱

外企场景
  • error

    Forgetting that the laser will eventually meet a receptor after a certain number of reflections, leading to inefficient simulation approaches.

  • error

    Not fully understanding the geometric pattern of laser reflections and attempting brute-force methods.

  • error

    Ignoring modular arithmetic’s role in optimizing the solution, leading to unnecessary calculations.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Different input values for p and q may lead to various patterns in laser reflections.

  • arrow_right_alt

    The problem can be extended to more complex room shapes or other configurations of mirrors.

  • arrow_right_alt

    You can explore performance optimizations by analyzing larger values for p and q.

help

常见问题

外企场景

镜面反射题解:数学·结合·几何 | LeetCode #858 中等