Skip to content

Latest commit

 

History

History
76 lines (66 loc) · 2.4 KB

539. Minimum Time Difference.md

File metadata and controls

76 lines (66 loc) · 2.4 KB

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.

Solution

  • Java

    • mine Runtime: 12 ms, faster than 52.90% of Java online submissions
    class Solution {
      public int findMinDifference(List<String> timePoints) {
          int len = timePoints.size();
          int[] array = new int[len];
          for (int i = 0; i < len; i++) {
              array[i] = format(timePoints.get(i));
          }
          Arrays.sort(array);
          int res = Integer.MAX_VALUE;
          int t;
          for (int i = 0; i < len; i++) {
              t = Math.abs(array[i] - array[(i + 1) % len]);
              if (t > 12 * 60) {
                  t = 24 * 60 - t;
              }
              res = Math.min(res, t);
          }
          return res;
      }
    
      private int format(String s) {
          String[] a = s.split(":");
          return Integer.parseInt(a[0]) * 60 + Integer.parseInt(a[1]);
      }
    }
    
    • most votes Runtime: 4 ms, faster than 89.39% of Java online submissions
    public class Solution {
        public int findMinDifference(List<String> timePoints) {
            boolean[] mark = new boolean[24 * 60];
            for (String time : timePoints) {
                String[] t = time.split(":");
                int h = Integer.parseInt(t[0]);
                int m = Integer.parseInt(t[1]);
                if (mark[h * 60 + m]) return 0;
                mark[h * 60 + m] = true;
            }
    
            int prev = 0, min = Integer.MAX_VALUE;
            int first = Integer.MAX_VALUE, last = Integer.MIN_VALUE;
            for (int i = 0; i < 24 * 60; i++) {
                if (mark[i]) {
                    if (first != Integer.MAX_VALUE) {
                        min = Math.min(min, i - prev);
                    }
                    first = Math.min(first, i);
                    last = Math.max(last, i);
                    prev = i;
                }
            }
    
            min = Math.min(min, (24 * 60 - last + first));
    
            return min;
        }
    }