C++ O(n) Solution


  • 0
    int getTime(string timePoint)
        {
            int i=0;
            while(timePoint[i]!=':') i++;
            int hour = stoi(timePoint.substr(0,i));
            int mins = stoi(timePoint.substr(i+1));
            return 60*hour + mins;
        }
    
        int findMinDifference(vector<string>& timePoints) {
            int n = timePoints.size();
            int gap = 1440;
            if(n>gap) return 0;
            vector<int> minutes(gap);
            for(auto tp : timePoints)
            {
                int t = getTime(tp);
                if(minutes[t] > 0) return 0;
                minutes[t] = 1;
            }
    
            int start = 0;
            while(minutes[start] == 0) start++;
    
            int res = gap;
            for(int i=start+1; start<gap; ++i)
            {
                int next = i % gap;
                if(minutes[next] != 0)
                {
                    res = min(res, (next - start + gap) % gap);
                    start = i;
                }
            }
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.