Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.

You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid.

Example 1:

  1. Input: "19:34"
  2. Output: "19:39"
  3. Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later.

Example 2:

  1. Input: "23:59"
  2. Output: "22:22"
  3. Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. It may be assumed that the returned time is next day's time since it is smaller than the input time numerically.

给一个时间,只能用原时间里的数字,求能组成的最近的下一个时间点,当下个时间点超过零点时,就当第二天的时间。

解法1:Brute fore, 由于给的时间只到分钟,一天中有1440个分钟,也就是1440个时间点,可以从当前时间点开始,遍历一天的1440个时间点,每到一个时间点,看其所有的数字是否在原时间点字符中存在,如果不存在,直接break,然后开始遍历下一个时间点,如果四个数字都存在,说明找到了,换算成题目的时间形式返回即可。

解法2:替换数字。先把出现的数字去重排序,然后从最低位的分钟开始替换,如果低位分钟上的数字已经是最大的数字,就把低位分钟上的数字换成最小的数字,否则就将低位分钟上的数字换成下一个较大的数字。高位分钟上的数字已经是最大的数字,或则下一个数字大于5,那么直接换成最小值,否则就将高位分钟上的数字换成下一个较大的数字。小时数字也是同理,小时低位上的数字情况比较复杂,当小时高位不为2的时候,低位可以是任意数字,而当高位为2时,低位需要小于等于3。对于小时高位,其必须要小于等于2。Time: O(4*10),Space: O(10)

解法3:找出这四个数字的所有可能的时间组合,然后和给定时间比较,maintain一个差值最小的,返回这个string。Time: O(4^4),Space: O(4)。

Java: 1

  1. class Solution {
  2. public String nextClosestTime(String time) {
  3. int hour = Integer.parseInt(time.substring(0, 2));
  4. int min = Integer.parseInt(time.substring(3, 5));
  5. while (true) {
  6. if (++min == 60) {
  7. min = 0;
  8. ++hour;
  9. hour %= 24;
  10. }
  11. String curr = String.format("%02d:%02d", hour, min);
  12. Boolean valid = true;
  13. for (int i = 0; i < curr.length(); ++i)
  14. if (time.indexOf(curr.charAt(i)) < 0) {
  15. valid = false;
  16. break;
  17. }
  18. if (valid) return curr;
  19. }
  20. }
  21. }  

Java: 2

  1. public String nextClosestTime(String time) {
  2. char[] t = time.toCharArray(), result = new char[4];
  3. int[] list = new int[10];
  4. char min = '9';
  5. for (char c : t) {
  6. if (c == ':') continue;
  7. list[c - '0']++;
  8. if (c < min) {
  9. min = c;
  10. }
  11. }
  12. for (int i = t[4] - '0' + 1; i <= 9; i++) {
  13. if (list[i] != 0) {
  14. t[4] = (char)(i + '0');
  15. return new String(t);
  16. }
  17. }
  18. t[4] = min;
  19. for (int i = t[3] - '0' + 1; i <= 5; i++) {
  20. if (list[i] != 0) {
  21. t[3] = (char)(i + '0');
  22. return new String(t);
  23. }
  24. }
  25. t[3] = min;
  26. int stop = t[0] < '2' ? 9 : 3;
  27. for (int i = t[1] - '0' + 1; i <= stop; i++) {
  28. if (list[i] != 0) {
  29. t[1] = (char)(i + '0');
  30. return new String(t);
  31. }
  32. }
  33. t[1] = min;
  34. for (int i = t[0] - '0' + 1; i <= 2; i++) {
  35. if (list[i] != 0) {
  36. t[0] = (char)(i + '0');
  37. return new String(t);
  38. }
  39. }
  40. t[0] = min;
  41. return new String(t);
  42. }  

Java: 3

  1. int diff = Integer.MAX_VALUE;
  2. String result = "";
  3.  
  4. public String nextClosestTime(String time) {
  5. Set<Integer> set = new HashSet<>();
  6. set.add(Integer.parseInt(time.substring(0, 1)));
  7. set.add(Integer.parseInt(time.substring(1, 2)));
  8. set.add(Integer.parseInt(time.substring(3, 4)));
  9. set.add(Integer.parseInt(time.substring(4, 5)));
  10.  
  11. if (set.size() == 1) return time;
  12.  
  13. List<Integer> digits = new ArrayList<>(set);
  14. int minute = Integer.parseInt(time.substring(0, 2)) * 60 + Integer.parseInt(time.substring(3, 5));
  15.  
  16. dfs(digits, "", 0, minute);
  17.  
  18. return result;
  19. }
  20.  
  21. private void dfs(List<Integer> digits, String cur, int pos, int target) {
  22. if (pos == 4) {
  23. int m = Integer.parseInt(cur.substring(0, 2)) * 60 + Integer.parseInt(cur.substring(2, 4));
  24. if (m == target) return;
  25. int d = m - target > 0 ? m - target : 1440 + m - target;
  26. if (d < diff) {
  27. diff = d;
  28. result = cur.substring(0, 2) + ":" + cur.substring(2, 4);
  29. }
  30. return;
  31. }
  32.  
  33. for (int i = 0; i < digits.size(); i++) {
  34. if (pos == 0 && digits.get(i) > 2) continue;
  35. if (pos == 1 && Integer.parseInt(cur) * 10 + digits.get(i) > 23) continue;
  36. if (pos == 2 && digits.get(i) > 5) continue;
  37. if (pos == 3 && Integer.parseInt(cur.substring(2)) * 10 + digits.get(i) > 59) continue;
  38. dfs(digits, cur + digits.get(i), pos + 1, target);
  39. }
  40. } 

Python:

  1. class Solution(object):
  2. def nextClosestTime(self, time):
  3. """
  4. :type time: str
  5. :rtype: str
  6. """
  7. h, m = time.split(":")
  8. curr = int(h) * 60 + int(m)
  9. result = None
  10. for i in xrange(curr+1, curr+1441):
  11. t = i % 1440
  12. h, m = t // 60, t % 60
  13. result = "%02d:%02d" % (h, m)
  14. if set(result) <= set(time):
  15. break
  16. return result

Python:

  1. class Solution(object):
  2. def nextClosestTime(self, time):
  3. """
  4. :type time: str
  5. :rtype: str
  6. """
  7. time = time[:2] + time[3:]
  8. isValid = lambda t: int(t[:2]) < 24 and int(t[2:]) < 60
  9. stime = sorted(time)
  10. for x in (3, 2, 1, 0):
  11. for y in stime:
  12. if y <= time[x]: continue
  13. ntime = time[:x] + y + (stime[0] * (3 - x))
  14. if isValid(ntime): return ntime[:2] + ':' + ntime[2:]
  15. return stime[0] * 2 + ':' + stime[0] * 2  

C++:

  1. class Solution {
  2. public:
  3. string nextClosestTime(string time) {
  4. string res = "0000";
  5. vector<int> v{600, 60, 10, 1};
  6. int found = time.find(":");
  7. int cur = stoi(time.substr(0, found)) * 60 + stoi(time.substr(found + 1));
  8. for (int i = 1, d = 0; i <= 1440; ++i) {
  9. int next = (cur + i) % 1440;
  10. for (d = 0; d < 4; ++d) {
  11. res[d] = '0' + next / v[d];
  12. next %= v[d];
  13. if (time.find(res[d]) == string::npos) break;
  14. }
  15. if (d >= 4) break;
  16. }
  17. return res.substr(0, 2) + ":" + res.substr(2);
  18. }
  19. };

C++:  

  1. class Solution {
  2. public:
  3. string nextClosestTime(string time) {
  4. string res = time;
  5. set<int> s{time[0], time[1], time[3], time[4]};
  6. string str(s.begin(), s.end());
  7. for (int i = res.size() - 1; i >= 0; --i) {
  8. if (res[i] == ':') continue;
  9. int pos = str.find(res[i]);
  10. if (pos == str.size() - 1) {
  11. res[i] = str[0];
  12. } else {
  13. char next = str[pos + 1];
  14. if (i == 4) {
  15. res[i] = next;
  16. return res;
  17. } else if (i == 3 && next <= '5') {
  18. res[i] = next;
  19. return res;
  20. } else if (i == 1 && (res[0] != '2' || (res[0] == '2' && next <= '3'))) {
  21. res[i] = next;
  22. return res;
  23. } else if (i == 0 && next <= '2') {
  24. res[i] = next;
  25. return res;
  26. }
  27. res[i] = str[0];
  28. }
  29. }
  30. return res;
  31. }
  32. };

  

  

All LeetCode Questions List 题目汇总

[LeetCode] 681. Next Closest Time 下一个最近时间点的更多相关文章

  1. [LeetCode] Next Closest Time 下一个最近时间点

    Given a time represented in the format "HH:MM", form the next closest time by reusing the ...

  2. LeetCode 681. Next Closest Time 最近时刻 / LintCode 862. 下一个最近的时间 (C++/Java)

    题目: 给定一个"HH:MM"格式的时间,重复使用这些数字,返回下一个最近的时间.每个数字可以被重复使用任意次. 保证输入的时间都是有效的.例如,"01:34" ...

  3. LeetCode 31. Next Permutation (下一个排列)

    Implement next permutation, which rearranges numbers into the lexicographically next greater permuta ...

  4. [LeetCode] Next Greater Element III 下一个较大的元素之三

    Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly th ...

  5. [LeetCode] Next Greater Element II 下一个较大的元素之二

    Given a circular array (the next element of the last element is the first element of the array), pri ...

  6. LeetCode 31 Next Permutation(下一个全排列)

    题目链接: https://leetcode.com/problems/next-permutation/?tab=Description   Problem :寻找给定int数组的下一个全排列(要求 ...

  7. LeetCode(31): 下一个排列

    Medium! 题目描述: (请仔细读题) 实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列. 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列) ...

  8. LeetCode第496题:下一个更大元素 I

    问题描述 给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集.找到 nums1 中每个元素在 nums2 中的下一个比其大的值. nums1 中数字 x ...

  9. [LeetCode] Next Greater Element I 下一个较大的元素之一

    You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of n ...

随机推荐

  1. Alpha冲刺随笔八:第八天

    课程名称:软件工程1916|W(福州大学) 作业要求:项目Alpha冲刺(十天冲刺) 团队名称:葫芦娃队 作业目标:在十天冲刺里对每天的任务进行总结. 随笔汇总:https://www.cnblogs ...

  2. python开发应用笔记-SciPy扩展库使用

    SciPy https://www.scipy.org/ SciPy中的数据结构: 1.ndarray(n维数组) 2.Series(变长字典) 3.DataFrame(数据框) NumPy适合于线性 ...

  3. linux下安装Sublime Text3并将它的快捷方式放进启动器中和卸载Sublime

    Sublime Text是一个代码编辑器,我主要是用它来编辑python.下面就来简单说明下它在linux的安装过程吧! 1.添加sublime text3的仓库 首先按下快捷键ctrl+alt+t打 ...

  4. 【python爬虫】动态html

    一.反爬策略 1.请求头 ——user-agent ——referer ——cookie 2.访问频率限制 ——代理池 ——再用户访问高峰期进行爬取,冲散日志.12-13 7-10 ——设置等待时长. ...

  5. php读取外部txt文件内容并打印在页面|fopen()函数

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  6. EntityFramework6 学习笔记(二)

    使用EF对数据库进行操作,整个过程就像操作数组一样,我们只管修改或向集合中添加值,最后通知EF保存修改后的结果就可以了. 准备工作 为了演示,我在数据库中建了两张表.class表用于表示班级,clas ...

  7. SIGAI机器学习第二十四集 聚类算法1

    讲授聚类算法的基本概念,算法的分类,层次聚类,K均值算法,EM算法,DBSCAN算法,OPTICS算法,mean shift算法,谱聚类算法,实际应用. 大纲: 聚类问题简介聚类算法的分类层次聚类算法 ...

  8. Python连接oracle数据库 例子一

    step1:下载cx_Oracle模块,cmd--pip install cx_Oracle step2: 1 import cx_Oracle #引用模块cx_Oracle 2 conn=cx_Or ...

  9. [bzoj1001]狼抓兔子 最小割

    题意概述:给出一张无向图,每条边有一个权值,割掉这条边代价为它的权值,求使起点不能到达终点的最小代价. 显然能看出这是个最小割嘛,然后最小割=最大流,建图的时候特殊处理一下再跑个最大流就好了. #in ...

  10. CSP-S乱搞记

    还有一年的时间,没人能挡住我前进的脚步 以后不打算写游记了,补完这篇再写就等退役吧,不太想传播什么负能量,走这条路,希望能得到自己想要的东西 Day-n 上了一个月文化课,班主任突然催我搞竞赛??? ...