LeetCode 🟢 3516. Find Closest Person
🔗 🟢 3516. Find Closest Person
Problem Statement
題目簡述
給定三個整數 、、,分別代表數線上三個人的位置:
- 人物 在 ;
- 人物 在 ;
- 人物 在 ,且保持不動。
人物 與人物 以相同速度朝人物 移動,判斷誰先到達人物 :
- 人物 先到達回傳
1; - 人物 先到達回傳
2; - 兩人同時到達回傳
0。
Constraints
約束條件
思路:距離比較
兩人速度相同,誰先到達完全取決於與 的距離:令 、,直接比較兩者大小即可:
- 若 ,人物 先到達,回傳 ;
- 若 ,人物 先到達,回傳 ;
- 若 ,同時到達,回傳 。
除了直接以條件運算式回傳外,也可用 位運算(Bit Manipulation) 把互斥的兩個布林結果壓成單一運算式 ((d1 > d2) << 1) | (d1 < d2):當 d1 > d2 為真時貢獻 ,d1 < d2 為真時貢獻 ,相等時兩者皆假、結果為 。
複雜度分析
- 時間複雜度:。
- 空間複雜度:。
Code
Python
1 | class Solution: |
C++
1 | class Solution { |
寫在最後
Cover Image Credit
The cover image was created by @柊栞zhongkan. All rights belong to the original artist.
If you are the copyright holder and believe this usage is inappropriate, please contact me by email or leave a comment. I will remove the image promptly.
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 十六個天亮!
評論
WalineGiscus





