LeetCode:539. Minimum Time Difference
来源:互联网 发布:java微信cms系统源码 编辑:程序博客网 时间:2024/06/05 00:11
Given a list of 24-hour clock time points in “Hour:Minutes” format, find the minimum minutes difference between any two time points in the list.
Example 1:
Input: ["23:59","00:00"]Output: 1
Note:
- The number of time points in the given list is at least 2 and won’t exceed 20000.
- The input time is legal and ranges from 00:00 to 23:59.
题意:求给定时间数组中两两之间最短的时间差。
分析:
两两时间差最短必然出现在大小相邻的两个数之间,所以首先进行时间排序。注意:由于时钟是圆形的,大小相邻还包括最大时间点和最小时间点之间的差,即循环时间差。
代码如下:
class Solution { final int hour=24*60; public int findMinDifference(List<String> timePoints) { Collections.sort(timePoints,new Comparator(){ @Override public int compare(Object o1,Object o2){ String s1=(String)o1; String s2=(String)o2; if(s1.split(":")[0].equals(s2.split(":")[0])) return (s1.split(":")[1].compareTo(s2.split(":")[1])); else return(s1.split(":")[0].compareTo(s2.split(":")[0])); } }); int min=timediff(timePoints.get(0),timePoints.get(timePoints.size()-1)); for(int i=1;i<timePoints.size();i++) { int temp=timediff(timePoints.get(i-1),timePoints.get(i)); if(min>temp) min=temp; } return min; } public int timediff(String ss1,String ss2){ int h1=Integer.parseInt(ss1.split(":")[0]); int m1=Integer.parseInt(ss1.split(":")[1]); int h2=Integer.parseInt(ss2.split(":")[0]); int m2=Integer.parseInt(ss2.split(":")[1]); int hdif=h2-h1; int mdif=m2-m1; int temp=hdif*60+mdif; return temp>hour/2?hour-temp:temp; }}
另外:忘记是哪家公司出过一个笔试题,求得是最大时间差。
分析:最大时间差必然是最靠近该时间旋转180度的那个时间,那么可以首先进行时间排序,然后遍历时间,二分查找旋转180度的时间点附近的那两个时间(如果没有把握确定是哪两个,可以把l-1,l,r,r+1都计算),然后计算时间差。
伪代码:
final day=24*60;sort(time);int max=0;for(int i=0;i<n;i++){ [l,r]=binFind((time[i]+day/2)%day); max=max(timeDiff(time[i],time[l-1]),max); max=max(timeDiff(time[i],time[l]),max); max=max(timeDiff(time[i],time[r]),max); max=max(timeDiff(time[i],time[r+1]),max);}return max;
阅读全文
0 0
- leetcode 539. Minimum Time Difference
- Leetcode-539. Minimum Time Difference
- [leetcode] 539. Minimum Time Difference
- [LeetCode]539. Minimum Time Difference
- LeetCode 539. Minimum Time Difference
- leetcode 539. Minimum Time Difference
- LeetCode 539. Minimum Time Difference
- leetcode 539. Minimum Time Difference
- LeetCode:539. Minimum Time Difference
- leetcode 539. Minimum Time Difference
- LeetCode笔记:539. Minimum Time Difference
- [Leetcode] 539. Minimum Time Difference 解题报告
- 539. Minimum Time Difference
- 539. Minimum Time Difference
- 539. Minimum Time Difference
- 539. Minimum Time Difference
- 539.Minimum Time Difference
- 【LeetCode 539】 Minimum Time Difference
- Apache beam其他学习记录
- 矩阵快速幂 [bzoi4000]棋盘
- 归并排序(优化版)
- linux中文件的批量创建与删除/改名
- 2017.8.8测试 题二 字符串的展开
- LeetCode:539. Minimum Time Difference
- mysql之路第一篇
- java for,while,do while循环
- Two Paths HDU 次短路问题
- 入门赛10
- 30读书笔记之多线程编程
- SpringBoot入门
- 最新版Sublime Text3 3143 注册码
- 用Java实现Dijkstra输出指定起点到终点的最短路径