【Python3】 LeetCode 7月挑战题目之14 - Angle Between Hands of a Clock

大家好,我是一个喜欢研究算法、机械学习和生物计算的小青年,我的CSDN博客是:一骑代码走天涯
如果您喜欢我的笔记,那么请点一下关注、点赞和收藏。如果內容有錯或者有改进的空间,也可以在评论让我知道。😄

第十四天问:Angle Between Hands of a Clock

题目连接: https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3390/

题目內容只有一句:现在给你报一个时钟时间,然后你要找出两支指针的最小夾角

所以,这道问题其实可以当做是纯粹的数学题,並不需要什么特別的算法才能找答案。

题目&示例 (引用自LeetCode)

Given two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand.

Example 1:

Input: hour = 12, minutes = 30
Output: 165
12:30有两个夾角,小的那个是165度

Example 2:

Input: hour = 3, minutes = 30
Output: 75
3:30有两个夾角,小的那个是75度

Example 3:

Input: hour = 3, minutes = 15
Output: 7.5
3:15有两个夾角,小的那个是7.5度

Constraints:

  1. 1 <= hour <= 12
  2. 0 <= minutes <= 59
  3. 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)         
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值