剑指 Offer II 035. 最小时间差(539. 最小时间差)

题目:

 

思路:

【1】先排序在进行相减获取最小差值,注意点:首先时钟是一个环,00:00和24:00是同一个时间,其次数字个数一共就24*60=1440个,所以超出了这个个数就必然会有重复的,也就是差值为0.

【2】使用哈希表计数的方式

代码展示:

使用哈希表计数的方式:

//时间4 ms击败70.88%
//内存42.6 MB击败37.91%
class Solution {
    public int findMinDifference(List<String> timePoints) {
        int n = timePoints.size();
        if (n > 1440) return 0;
        int[] cnts = new int[1440 * 2 + 10];
        for (String s : timePoints) {
            String[] ss = s.split(":");
            int h = Integer.parseInt(ss[0]), m = Integer.parseInt(ss[1]);
            cnts[h * 60 + m]++;
            cnts[h * 60 + m + 1440]++;
        }
        int ans = 1440, last = -1;
        for (int i = 0; i <= 1440 * 2 && ans != 0; i++) {
            if (cnts[i] == 0) continue;
            if (cnts[i] > 1) ans = 0;
            else if (last != -1) ans = Math.min(ans, i - last);
            last = i;
        }
        return ans;
    }
}

 

先排序在进行相减获取最小差值的方式:

//时间2 ms击败96.98%
//内存41.3 MB击败62.64%
class Solution {
    public int findMinDifference(List<String> timePoints) {
        if (timePoints.size() < 2 || timePoints.size() > 1440) return 0;

        Collections.sort(timePoints);
        int ans = Integer.MAX_VALUE;
        int t0Minutes = getMinutes(timePoints.get(0));
        int preMinutes = t0Minutes;
        for (int i = 1; i < timePoints.size(); ++i) {
            int minutes = getMinutes(timePoints.get(i));
            ans = Math.min(ans, minutes - preMinutes); // 相邻时间的时间差
            preMinutes = minutes;
        }
        ans = Math.min(ans, t0Minutes + 1440 - preMinutes); // 首尾时间的时间差
        return ans;
    }

    public int getMinutes(String t) {
        return ((t.charAt(0) - '0') * 10 + (t.charAt(1) - '0')) * 60 + (t.charAt(3) - '0') * 10 + (t.charAt(4) - '0');
    }
}
//时间3 ms击败80.91%
//内存40.9 MB击败90.52%
//也可以先考虑转换成为数字,再排序【这种相对消耗的空间更小】
class Solution {
    public int findMinDifference(List<String> timePoints) {
        if (timePoints.size() < 2 || timePoints.size() > 1440) return 0;

        int n = timePoints.size() * 2;
        int[] nums = new int[n];
        for (int i = 0, idx = 0; i < n / 2; i++, idx += 2) {
            String[] ss = timePoints.get(i).split(":");
            int h = Integer.parseInt(ss[0]), m = Integer.parseInt(ss[1]);
            nums[idx] = h * 60 + m;
            nums[idx + 1] = nums[idx] + 1440;
        }
        Arrays.sort(nums);
        int ans = nums[1] - nums[0];
        for (int i = 0; i < n - 1; i++) ans = Math.min(ans, nums[i + 1] - nums[i]);
        return ans;
    }
}

 

posted @ 2023-03-13 15:46  忧愁的chafry  阅读(15)  评论(0编辑  收藏  举报