leetcode 539. Minimum Time Difference 题解【C++ & Java & Python】

题目链接

539. Minimum Time Difference
539. 最小时间差

题解

先对所有时间按升序排序,然后逐一获取两个相邻时间的时间差。由于时间是24小时循环的,两个时间之间有两个时间差,例如00:0023:59, 就有11440-1两个时间差。其中144024小时的分钟数。任何一个时间差timeDiff,都有一个对应的1440-timeDiff,两者取较小值。遍历过程中,求全局最小值res, 每次获取新的timeDiff都需要和res比较,如果timeDiff更小则更新res

C++

class Solution {
public:
    int findMinDifference(vector<string>& timePoints) {
        int n = timePoints.size();
        int res  = 24 * 60;
        sort(timePoints.begin(), timePoints.end()); //对所有时间按从小到大排序
        for(int i = 0; i < n; i++) {
            int diff = timeDiff(timePoints[i], timePoints[(i+1)%n]);//比较相邻时间的时间差
            diff = min( 24 * 60 - diff, diff);// 两个时间的时间差有两个,因为时间是24小时制循环的
            res = min(res, diff);//获取全局的最小时间
        }
        return res;
    }

private:
    int timeDiff(string t1, string t2) {
        int h1 = stoi(t1.substr(0, 2));
        int m1 = stoi(t1.substr(3, 2));
        int h2 = stoi(t2.substr(0, 2));
        int m2 = stoi(t2.substr(3, 2));
        return abs((h1-h2)*60 + (m1-m2));
    }
};

Java

class Solution {
    public int findMinDifference(List<String> timePoints) {
        int n = timePoints.size();
        Collections.sort(timePoints); //对所有时间排序
        int res = 1440; // 24 * 60
        for(int i = 0; i < n; i++) {
            int diff = timeDiff(timePoints.get(i), timePoints.get((i+1)%n)); //获取时间差
            diff = Math.min(diff, 1440-diff);//由于时间24小时循环,两个时间之间会有2个时间差,取较小者
            res = Math.min(res, diff);//获取较小的时间差
        }
        return res;
    }

    private int timeDiff(String s1, String s2) {//获取两个时间的时间差
        int h1 = Integer.valueOf(s1.substring(0, 2));
        int m1 = Integer.valueOf(s1.substring(3, 5));
        int h2 = Integer.valueOf(s2.substring(0, 2));
        int m2 = Integer.valueOf(s2.substring(3, 5));
        return Math.abs((h1-h2)*60 + (m1-m2));
    }
}

Python

class Solution(object):
    def findMinDifference(self, timePoints):
        """
        :type timePoints: List[str]
        :rtype: int
        """
        n = len(timePoints)
        timePoints.sort() # 对时间进行排序
        res = 24 * 60  # 1440
        for i in range(n):
            diff = self.timeDiff(timePoints[i], timePoints[(i+1)%n]) # 获取时间差
            diff = min(diff, 1440 - diff) # 时间是24小时循环的,因此有两个时间差,取较小者
            res = min(diff, res) # 获取全局的最小时间差
        return res

    def timeDiff(self, t1, t2): # 获取两个时间的时间差
        h1 = int(t1[0:2])
        m1 = int(t1[3:5])
        h2 = int(t2[0:2])
        m2 = int(t2[3:5])
        return abs((h1-h2)*60 + (m1-m2))  

猜你喜欢

转载自blog.csdn.net/androidchanhao/article/details/81297006