• 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;
        }
    }
  • 相关阅读:
    sqlite android
    cocos2dx 2.1.3 使用json
    cocos2dandroid 自动缩放、高清显示
    cocos2dx HttpClient
    coco2dx 2.1.3 之 使用网络请求
    facebook on android
    项目运行出错怎么办?
    Bug应对策略 本文系转
    从网页中导入Excel
    ASP.NET HTTP运行时组成详解[转帖]
  • 原文地址:https://www.cnblogs.com/fatttcat/p/13601250.html
Copyright © 2020-2023  润新知