LeetCode.539 Minimum Time Difference(求时间最小间隔)

题目

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 {
    public int findMinDifference(List<String> timePoints) {
        // 思路:找出时间列表中的最小间隔,将所有时间放在统一时间数组内,之后进行加减
        if (timePoints == null || timePoints.size() == 0) {
            return 0;
        }
        int[] timeArr = new int[24 * 60];
        for (String time : timePoints) {
            int index = convertTimeIndex(time);
            timeArr[index]++;
        }
        // 求时间间隔
        int minIndex = timeArr.length + 1;
        int maxIndex = 0;
        int curIndex = -1;
        int lastIndex = -1;
        int count = 0;
        int mixResult = timeArr.length + 1;
        for (int i = 0; i < timeArr.length; i++) {
            if (timeArr[i] > 0) {
                count++;
                curIndex = i;
                // 存在相同的
                if (timeArr[i] > 1) {
                    mixResult = 0;
                    return mixResult;
                }
                if (count > 1) {
                    // 确保存在两次不同的值
                    mixResult = Math.min(mixResult, curIndex - lastIndex);
                }
                // 交换对应的值
                minIndex = Math.min(minIndex, curIndex);
                maxIndex = Math.max(maxIndex, curIndex);
                lastIndex = curIndex;
            }
        }
        return mixResult == 0 ? mixResult : Math.min(mixResult, minIndex + timeArr.length - maxIndex);
    }
    
    public int convertTimeIndex(String time){
        if (time == null || time.length() == 0) {
            return 0;
        }
        String[] timeArr = time.split(":");
        String hour = timeArr[0];
        String min = timeArr[1];
        return Integer.valueOf(hour) * 60 + Integer.valueOf(min);
    }
}

你可能感兴趣的:(LeetCode算法编程,Java基础学习)