跳转至

1344. 时钟指针的夹角

题目描述

给你两个数 hour 和 minutes 。请你返回在时钟上,由给定时间的时针和分针组成的较小角的角度(60 单位制)。

 

示例 1:

输入:hour = 12, minutes = 30
输出:165

示例 2:

输入:hour = 3, minutes = 30
输出;75

示例 3:

输入:hour = 3, minutes = 15
输出:7.5

示例 4:

输入:hour = 4, minutes = 50
输出:155

示例 5:

输入:hour = 12, minutes = 0
输出:0

 

提示:

  • 1 <= hour <= 12
  • 0 <= minutes <= 59
  • 与标准答案误差在 10^-5 以内的结果都被视为正确结果。

解法

方法一:数学

时针每小时移动 30 度,每分钟移动 0.5 度。分针每分钟移动 6 度。如果指针之间的夹角大于 180 度,则取其与 360 度的差值,以确保获得最小的夹角。

时间复杂度 $O(1)$,空间复杂度 $O(1)$。

1
2
3
4
5
6
class Solution:
    def angleClock(self, hour: int, minutes: int) -> float:
        h = 30 * hour + 0.5 * minutes
        m = 6 * minutes
        diff = abs(h - m)
        return min(diff, 360 - diff)
1
2
3
4
5
6
7
8
class Solution {
    public double angleClock(int hour, int minutes) {
        double h = 30 * hour + 0.5 * minutes;
        double m = 6 * minutes;
        double diff = Math.abs(h - m);
        return Math.min(diff, 360 - diff);
    }
}
1
2
3
4
5
6
7
8
9
class Solution {
public:
    double angleClock(int hour, int minutes) {
        double h = 30 * hour + 0.5 * minutes;
        double m = 6 * minutes;
        double diff = abs(h - m);
        return min(diff, 360 - diff);
    }
};
1
2
3
4
5
6
func angleClock(hour int, minutes int) float64 {
    h := 30*float64(hour) + 0.5*float64(minutes)
    m := 6 * float64(minutes)
    diff := math.Abs(h - m)
    return math.Min(diff, 360-diff)
}
1
2
3
4
5
6
function angleClock(hour: number, minutes: number): number {
    const h = 30 * hour + 0.5 * minutes;
    const m = 6 * minutes;
    const diff = Math.abs(h - m);
    return Math.min(diff, 360 - diff);
}

评论