[LeetCode] 539. Minimum Time Difference
阿新 • • 發佈:2020-07-24
Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimumminutesdifference 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.
最小時間差。題意是給一些以字串list表示的時間,請你找出這中間最小的時間差。例子給的不是很好,因為list不止兩個元素。
這道題不涉及演算法,不過最優解比較考驗你對時間的敏感度。首先,既然時間是在00:00 - 23:59這個範圍內被表示出來,所以最壞也就是1440種情況,所以可以建立一個長度為1440的布林陣列記錄哪些時間出現過。之後遍歷這個布林陣列,看看哪兩個時間之間的時間差最小。注意記得去“模”24小時。
時間O(n)
空間O(n)
Java實現
1 class Solution { 2 public int findMinDifference(List<String> timePoints) {3 boolean[] mark = new boolean[24 * 60]; 4 for (String time : timePoints) { 5 String[] t = time.split(":"); 6 int h = Integer.parseInt(t[0]); 7 int m = Integer.parseInt(t[1]); 8 if (mark[h * 60 + m]) { 9 return 0; 10 }11 mark[h * 60 + m] = true; 12 } 13 14 int prev = 0; 15 int min = Integer.MAX_VALUE; 16 int first = Integer.MAX_VALUE; 17 int last = Integer.MIN_VALUE; 18 for (int i = 0; i < 24 * 60; i++) { 19 if (mark[i]) { 20 if (first != Integer.MAX_VALUE) { 21 min = Math.min(min, i - prev); 22 } 23 first = Math.min(first, i); 24 last = Math.max(last, i); 25 prev = i; 26 } 27 } 28 min = Math.min(min, (24 * 60 - last + first)); 29 return min; 30 } 31 }