Java 5 ms Straight Forward Solution Without dfs


  • 0
    K
    class Solution {
        public String nextClosestTime(String time) {
            int[] nums= new int[4];
            nums[0]=time.charAt(0)-'0';
            nums[1]=time.charAt(1)-'0';
            nums[2]=time.charAt(3)-'0';
            nums[3]=time.charAt(4)-'0';
            int i=3,change=0;
            for(;i>=0;i--){
                change= findNextGreater(nums,i);
                if(change!=-1) break;
            }
            int min=findMin(nums);
            if(i>=0) nums[i]=change;
            i++;
            for(;i<4;i++) nums[i]=min;
            
            return ""+nums[0]+nums[1]+":"+nums[2]+nums[3];
            
        }
        public int findMin(int[] nums){
            int min=10;
            for(int i=0;i<4;i++)
                min=Math.min(min,nums[i]);
            return min;
        }
        
        public int findNextGreater(int[] nums,int i){
            int max=0;
            if(i==3) max=9;
            if(i==2) max=5;
            if(i==1){
                if(nums[0]<=1) max=9;
                else max=3;
            }
            if(i==0) max=2;
            int res=10;
            if(nums[i]==max) return -1;
            for(int j=0;j<4;j++){
                if(j==i) continue;
                if(nums[j]<=max && nums[j]>nums[i] && nums[j]<res) res=nums[j]; 
            }
            return res==10? -1: res;
        }
    } 
    

Log in to reply
 

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