zoukankan      html  css  js  c++  java
  • 949. Largest Time for Given Digits

    Given an array of 4 digits, return the largest 24 hour time that can be made.

    The smallest 24 hour time is 00:00, and the largest is 23:59.  Starting from 00:00, a time is larger if more time has elapsed since midnight.

    Return the answer as a string of length 5.  If no valid time can be made, return an empty string.

    Example 1:

    Input: [1,2,3,4]
    Output: "23:41"
    

    Example 2:

    Input: [5,5,5,5]
    Output: ""
    

    Note:

    1. A.length == 4
    2. 0 <= A[i] <= 9

    permutation + backtracking

    time = O(1) -- length of the array is fixed, space = O(1)

    class Solution {
        
        private int maxTime = -1;
        
        public String largestTimeFromDigits(int[] A) {
            maxTime = -1;
            permute(A, 0);
            if(maxTime == -1) {
                return "";
            } else {
                return String.format("%02d:%02d", maxTime / 60, maxTime % 60);
            }
        }
        
        private void permute(int[] arr, int start) {
            if(start == arr.length) {
                buildTime(arr);
                return;
            }
            for(int i = 0; i < arr.length; i++) {
                swap(arr, i, start);
                permute(arr, start + 1);
                swap(arr, i, start);
            }
        }
        
        private void buildTime(int[] arr) {
            int hour = arr[0] * 10 + arr[1];
            int minute = arr[2] * 10 + arr[3];
            if(hour < 24 && minute < 60) {
                maxTime = Math.max(maxTime, hour * 60 + minute);
            }
        }
        
        private void swap(int[] arr, int i, int j) {
            int tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
        }
    }
  • 相关阅读:
    Another mysql daemon already running with the same unix socket
    cloud maintenance of OpenNebula
    内核分析阅读笔记
    eucalyptus,openNebula云构建漫谈
    quotation
    Adress
    cos
    COS回应7大质疑
    linux内核地址mapping
    开源 免费 java CMS
  • 原文地址:https://www.cnblogs.com/fatttcat/p/13601250.html
Copyright © 2011-2022 走看看