Java Straight approach


  • 0
    J

    idea: Scan from the right, if we can find next higher value and mm or hh is also valid, then return its value. otherwise replace it with the min value in the all digits.

    public String nextClosestTime(String time) {
           char[] digits=new char[4];
           int i=0;
           for(char c : time.toCharArray()){
               if(c!=':'){
                   digits[i++]=c;
               }
           }
           Arrays.sort(digits);
           String[] strArray=time.split(":");
           char[] hh=strArray[0].toCharArray();
           char[] mm=strArray[1].toCharArray();
          
           for(int m=1;m>=0;m--){
              i=Arrays.binarySearch(digits,mm[m]);
              while(i<4){
                   if(digits[i]>mm[m]){
                       mm[m]=digits[i];
                       if(Integer.parseInt(new String(mm))<60){
                           return new String(hh)+":"+new String(mm);
                       }
                       break;
                   }
                   i++;
               }
               mm[m]=digits[0];
           }
    
           //for hour
         for(int m=1;m>=0;m--){
             i=Arrays.binarySearch(digits,hh[m]);
              while(i<4){
                   if(digits[i]>hh[m]){
                       hh[m]=digits[i];
                       if(Integer.parseInt(new String(hh))<24){
                           return new String(hh)+":"+new String(mm);
                       }
                       break;
                   }
                   i++;
               }
               hh[m]=digits[0];
           }
          return new String(hh)+":"+new String(mm);  
           
       }
    
    

Log in to reply
 

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