clueless coding // TODO: be smarter

LeetCode Minimum Time Difference: CPP Solution



TL;DR Code Solution



int convertToInt(string input) {

    int result = 0;
    for (int i = 0; i < input.length(); i++) {
        result *= 10;
        result += input[i] - '0';
    }
    return result;

}

int compareTimes(vector<int> a, vector<int> b) {

    if (a[0] < b[0]) {
        return (24 * 60) - compareTimes(b, a);
    }

    int hours = a[0] - b[0];
    int minutes = a[1] - b[1];

    return 60 * hours + minutes;

}

int findMinDifference(vector<string>& timePoints) {

    vector<vector<int>> times;
    for (int i = 0; i < timePoints.size(); i++) {
        vector<int> time(2);
        time[0] = convertToInt(timePoints[i].substr(0, 2));
        time[1] = convertToInt(timePoints[i].substr(3, 5));
        times.push_back(time);
    }

    sort(times.begin(), times.end(), [](vector<int>& a, vector<int>& b) {
        return a[0] < b[0] || (a[0] == b[0] && a[1] < b[1]);
    });
    times.push_back(times[0]);

    int result = INT_MAX;
    for (int i = 1; i < times.size(); i++) {
        result = min(result, abs(compareTimes(times[i], times[i-1])));
    }

    return result;

}