算法
(模拟) $O(1)$
一种思路是分别计算出时针与0
时刻的夹角,以及分针与0
时刻的夹角,然后对二者求一个绝对差,而由于可能会是钝角,所以得取min(dist, 360 - dist)
另一种思路是十分和分针的夹角是5.4 * (hour * 60 + minutes) % 360
,然后取小于等于$180$度的角
Java 代码
class Solution {
public double angleClock(int hour, int minutes) {
// 360 / 12 = 30
// 360 / 60 = 6
double hourHand = (hour + minutes / 60.0) * 30;
double minHand = minutes * 6;
double dist = Math.abs(hourHand - minHand);
return Math.min(dist, 360 - dist);
}
}
Python 代码
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
angle = 5.5 * (hour * 60 + minutes) % 360
return angle if angle <= 180 else 360 - angle