前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发,mcf171专栏。这次比赛略无语,没想到前3题都可以用暴力解。
博客链接:mcf171的博客
——————————————————————————————
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. 这个题目先排序,然后排序之后比较相邻的两个点之前,然后最后比较第一个元素和最后一个元素。 public class Solution { public int findMinDifference(List<String> timePoints) { int min = Integer.MAX_VALUE; Collections.sort(timePoints,new Comparator<String>(){ @Override public int compare(String o1, String o2) { String[] time1 = o1.split(":"); String[] time2 = o2.split(":"); int result1 = Integer.parseInt(time1[0]) * 60 + Integer.parseInt(time1[1]); int result2 = Integer.parseInt(time2[0]) * 60 + Integer.parseInt(time2[1]); return result1 - result2; } }); for(int i = 0; i < timePoints.size() - 1; i ++){ String[] time1 = timePoints.get(i).split(":"); String[] time2 = timePoints.get(i+1).split(":"); int result1 = Integer.parseInt(time1[0]) * 60 + Integer.parseInt(time1[1]); int result2 = Integer.parseInt(time2[0]) * 60 + Integer.parseInt(time2[1]); if(min >= result2 - result1) min = result2 - result1; } String[] time1 = timePoints.get(0).split(":"); String[] time2 = timePoints.get(timePoints.size() - 1).split(":"); int result1 = Integer.parseInt(time1[0]) * 60 + Integer.parseInt(time1[1]); int result2 = Integer.parseInt(time2[0]) * 60 + Integer.parseInt(time2[1]); if(min >= result2 - result1) min = result2 - result1; if(min >= result1 + 24* 60 - result2) min = result1 + 24* 60 - result2; return min; } }