Lengthy Python beats 100% (42 ms)


  • 2
    # 62 / 62 test cases passed.
    # Status: Accepted
    # Runtime: 42 ms
    class Solution(object):
        def nextClosestTime(self, time):
            num1 = int(time[0])
            num2 = int(time[1])
            num3 = int(time[3])
            num4 = int(time[4])
            rank = [num1,num2,num3,num4]
            rank = sorted(rank)
            
            def h(a, cur):
                res = 0
                for i in range(len(a)):
                    if a[i] == cur:
                        res = i
                return res
            if num4 < rank[3]: 
                return str(num1)+str(num2)+":"+str(num3)+str(rank[h(rank, num4)+1])
            ind3 = h(rank, num3)
            if ind3 < 3: 
                cur = rank[ind3+1]
                if cur < 6:  return str(num1)+str(num2)+":"+str(cur)+str(rank[0])
                
            ind2 = h(rank, num2)
            if ind2 < 3:
                if num1 == 2:
                    cur = rank[ind2+1]
                    if cur < 4:
                        return str(num1)+str(cur)+":"+str(rank[0])+str(rank[0])
                else:
                    cur = rank[ind2+1]
                    return str(num1)+str(cur)+":"+str(rank[0])+str(rank[0])
            ind1 = h(rank,num1)
            if ind1 < 3:
                cur = rank[ind1 + 1]
                if cur < 3:
                    return str(cur)+str(rank[0])+":"+str(rank[0])+str(rank[0])
            
            return str(rank[0])+str(rank[0])+":"+str(rank[0])+str(rank[0])
    

  • 0

    Exact the same idea, similar time (~40ms):

        def nextClosestTime(self, time):
            isV = lambda t: t[:2] < '24' and t[3:] < '60'
            can = sorted(set(time))[:-1]
            for i in (4, 3, 1, 0):
                for n in can[can.index(time[i])+1:]:
                    ntime = (time[:i] + n).ljust(5, can[0])
                    if isV(ntime):
                        return ntime[:2] + ':' + ntime[3:]
                    else:
                        break
            return can[0]*2 + ':' + can[0]*2
    

    Update, another one, still the same idea with slightly different tricks on dealing corner cases (also ~40ms).

        def nextClosestTime(self, time):
            pos = sorted(set(time))[:-1]
            nxt = dict(zip(pos, pos[1:] + ['']))
            isV = lambda t: t[:2] < '24' and t[3:] < '60'
    
            for i in (4, 3, 1, 0):
                n = nxt[time[i]]
                res = (time[:i] + n).ljust(5, pos[0])
                if n and isV(res): break
            else:
                res = pos[0] * 5
            return res[:2] + ':' + res[3:]
    

    But I have to say both are ugly as hell


  • 0
    A

    can you explain it with example?


Log in to reply
 

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