大家好,我是一个喜欢研究算法、机械学习和生物计算的小青年,我的CSDN博客是:一骑代码走天涯
如果您喜欢我的笔记,那么请点一下关注、点赞和收藏。如果內容有錯或者有改进的空间,也可以在评论让我知道。😄
目录/Table of Content
第十四天问:Angle Between Hands of a Clock
题目內容只有一句:现在给你报一个时钟时间,然后你要找出两支指针的最小夾角。
所以,这道问题其实可以当做是纯粹的数学题,並不需要什么特別的算法才能找答案。
题目&示例 (引用自LeetCode)
Given two numbers,
hour
andminutes
. Return the smaller angle (in degrees) formed between thehour
and theminute
hand.
Example 1:
Input: hour = 12, minutes = 30
Output: 165
Example 2:
Input: hour = 3, minutes = 30
Output: 75
Example 3:
Input: hour = 3, minutes = 15
Output: 7.5
Constraints:
1 <= hour <= 12
0 <= minutes <= 59
- Answers within
10^-5^
of the actual value will be accepted as correct.
解题思路
要解这题不难,只需要找出几个数字就可以做到了。首先,我们要知道 时针和分针分別在时钟哪个位置 (或者说,角度是多少)。先用12点位置作为起始参考点,再计算两支指针分別有多少度 (360o为一个全圆形,分別除以12和60就是每一小时和每一分钟所增加的角度),然后再把每一小时的间距除以60作为同一小时內不同分钟对时针位置的影响。最后,找他们的最小相差便是答案了。
代码 (找出两个夾角再求最小)
时间复杂度:O(1)
空间复杂度:O(1)
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
minute_unit = 360/60
hour_unit = 360/12
fine_tune_hour_unit = (360/12)/60
# calculate which angle the minute is
minute_angle = minute_unit * minutes
# calculate which angle the hour is
hour_angle = hour_unit * hour
if hour_angle == 360:
hour_angle = 0
hour_angle += fine_tune_hour_unit * minutes
# find out both angles between them
angle_a = hour_angle - minute_angle
if angle_a < 0:
angle_a = 360 + angle_a
angle_b = minute_angle - hour_angle
if angle_b < 0:
angle_b = 360 + angle_b
# take the minimum as the answer
return min(angle_a, angle_b)