C# consice code that is intuitive and looks different from popular answers


  • 0
    M
    1. Start from the last digit, find the minimal digit that is larger than it. If found set it to the last digit, and return the result directly.
    2. If not, continue the same process with the second to last digit. Once found and set the current digit, set everything after it as the minimal value of the 4 digits
    3. If never found in above steps, set everything as the minimal value of the 4 digits
    public string NextClosestTime(string time) {
            int HH = time[0]-'0';
            int HL = time[1]-'0';
            int MH = time[3]-'0';
            int ML = time[4]-'0';
            
            int[] digits = new int[]{HH,HL,MH,ML};
            Array.Sort(digits);
            
            int min = digits[0];
            for(int i=0; i<4; i++) if (digits[i] > ML) {ML=digits[i]; return ""+HH+HL+":"+MH+ML;}
            for(int i=0; i<4; i++) if (digits[i] > MH && digits[i]<6) {MH=digits[i];ML=min; return ""+HH+HL+":"+MH+ML;}
            for(int i=0; i<4; i++) if (digits[i] > HL && (HH==1||HH==0||HH==2&&digits[i]<4)) {HL=digits[i];MH=min;ML=min; return ""+HH+HL+":"+MH+ML;}
            for(int i=0; i<4; i++) if (digits[i] > HH && digits[i]<3) {HH=digits[i]; HL=min;MH=min;ML=min; return ""+HH+HL+":"+MH+ML;}
            
            return ""+min+min+":"+min+min;
        } 
    

Log in to reply
 

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