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:

Input: "19:34"
Output: "19:39"
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:

Input: "23:59"
Output: "22:22"
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

class Solution {
public String nextClosestTime(String time) {
int hour = Integer.parseInt(time.substring(0, 2));
int min = Integer.parseInt(time.substring(3, 5));
while (true) {
if (++min == 60) {
min = 0;
++hour;
hour %= 24;
}
String curr = String.format("%02d:%02d", hour, min);
Boolean valid = true;
for (int i = 0; i < curr.length(); ++i)
if (time.indexOf(curr.charAt(i)) < 0) {
valid = false;
break;
}
if (valid) return curr;
}
}
}  

Java: 2

public String nextClosestTime(String time) {
char[] t = time.toCharArray(), result = new char[4];
int[] list = new int[10];
char min = '9';
for (char c : t) {
if (c == ':') continue;
list[c - '0']++;
if (c < min) {
min = c;
}
}
for (int i = t[4] - '0' + 1; i <= 9; i++) {
if (list[i] != 0) {
t[4] = (char)(i + '0');
return new String(t);
}
}
t[4] = min;
for (int i = t[3] - '0' + 1; i <= 5; i++) {
if (list[i] != 0) {
t[3] = (char)(i + '0');
return new String(t);
}
}
t[3] = min;
int stop = t[0] < '2' ? 9 : 3;
for (int i = t[1] - '0' + 1; i <= stop; i++) {
if (list[i] != 0) {
t[1] = (char)(i + '0');
return new String(t);
}
}
t[1] = min;
for (int i = t[0] - '0' + 1; i <= 2; i++) {
if (list[i] != 0) {
t[0] = (char)(i + '0');
return new String(t);
}
}
t[0] = min;
return new String(t);
}  

Java: 3

int diff = Integer.MAX_VALUE;
String result = ""; public String nextClosestTime(String time) {
Set<Integer> set = new HashSet<>();
set.add(Integer.parseInt(time.substring(0, 1)));
set.add(Integer.parseInt(time.substring(1, 2)));
set.add(Integer.parseInt(time.substring(3, 4)));
set.add(Integer.parseInt(time.substring(4, 5))); if (set.size() == 1) return time; List<Integer> digits = new ArrayList<>(set);
int minute = Integer.parseInt(time.substring(0, 2)) * 60 + Integer.parseInt(time.substring(3, 5)); dfs(digits, "", 0, minute); return result;
} private void dfs(List<Integer> digits, String cur, int pos, int target) {
if (pos == 4) {
int m = Integer.parseInt(cur.substring(0, 2)) * 60 + Integer.parseInt(cur.substring(2, 4));
if (m == target) return;
int d = m - target > 0 ? m - target : 1440 + m - target;
if (d < diff) {
diff = d;
result = cur.substring(0, 2) + ":" + cur.substring(2, 4);
}
return;
} for (int i = 0; i < digits.size(); i++) {
if (pos == 0 && digits.get(i) > 2) continue;
if (pos == 1 && Integer.parseInt(cur) * 10 + digits.get(i) > 23) continue;
if (pos == 2 && digits.get(i) > 5) continue;
if (pos == 3 && Integer.parseInt(cur.substring(2)) * 10 + digits.get(i) > 59) continue;
dfs(digits, cur + digits.get(i), pos + 1, target);
}
} 

Python:

class Solution(object):
def nextClosestTime(self, time):
"""
:type time: str
:rtype: str
"""
h, m = time.split(":")
curr = int(h) * 60 + int(m)
result = None
for i in xrange(curr+1, curr+1441):
t = i % 1440
h, m = t // 60, t % 60
result = "%02d:%02d" % (h, m)
if set(result) <= set(time):
break
return result

Python:

class Solution(object):
def nextClosestTime(self, time):
"""
:type time: str
:rtype: str
"""
time = time[:2] + time[3:]
isValid = lambda t: int(t[:2]) < 24 and int(t[2:]) < 60
stime = sorted(time)
for x in (3, 2, 1, 0):
for y in stime:
if y <= time[x]: continue
ntime = time[:x] + y + (stime[0] * (3 - x))
if isValid(ntime): return ntime[:2] + ':' + ntime[2:]
return stime[0] * 2 + ':' + stime[0] * 2  

C++:

class Solution {
public:
string nextClosestTime(string time) {
string res = "0000";
vector<int> v{600, 60, 10, 1};
int found = time.find(":");
int cur = stoi(time.substr(0, found)) * 60 + stoi(time.substr(found + 1));
for (int i = 1, d = 0; i <= 1440; ++i) {
int next = (cur + i) % 1440;
for (d = 0; d < 4; ++d) {
res[d] = '0' + next / v[d];
next %= v[d];
if (time.find(res[d]) == string::npos) break;
}
if (d >= 4) break;
}
return res.substr(0, 2) + ":" + res.substr(2);
}
};

C++:  

class Solution {
public:
string nextClosestTime(string time) {
string res = time;
set<int> s{time[0], time[1], time[3], time[4]};
string str(s.begin(), s.end());
for (int i = res.size() - 1; i >= 0; --i) {
if (res[i] == ':') continue;
int pos = str.find(res[i]);
if (pos == str.size() - 1) {
res[i] = str[0];
} else {
char next = str[pos + 1];
if (i == 4) {
res[i] = next;
return res;
} else if (i == 3 && next <= '5') {
res[i] = next;
return res;
} else if (i == 1 && (res[0] != '2' || (res[0] == '2' && next <= '3'))) {
res[i] = next;
return res;
} else if (i == 0 && next <= '2') {
res[i] = next;
return res;
}
res[i] = str[0];
}
}
return res;
}
};

  

  

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. 微信小程序~下拉刷新真机测试不弹回的处理办法

    问题描述: 下拉刷新在手机上不会自动回弹,开发工具可以 解决办法: 主动调用wx.stopPullDownRefresh /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDow ...

  2. AT2000 Leftmost Ball

    设\(f[i][j]\)表示当前有\(i\)个白球,一共放完了\(j\)种球 显然有\(j <= i\) 对于每个状态目前已经放下去的球是固定了的,那么考虑转移 放白球 从\(f[i - 1][ ...

  3. Hibernate的悲观锁和乐观锁

    前一篇博客我们从数据库角度分析,锁可以分为三种,分别为共享锁,独占锁和更新锁.我们从程序的角度来看锁可以分为两种类型,悲观锁和乐观锁,Hibernate提供对这两种锁 的支持,我们来了解一下Hiber ...

  4. 题解 UVa11076

    题目大意 多组数据,每组数据给出 \(n\) 个一位数,求出这些一位数组成的所有不同整数的和. 分析 考虑一个数对某一位的贡献,为这个数乘以其他数的全排列数,问题转化为可重复元素的全排列. 引理 \( ...

  5. Node.js是什么?提供了哪些内容?

    什么是Node.js? Node.js是基于Chrome V8 引擎的 JavaScript运行时(运行环境). Node.js提供了哪些内容? Node.js运行时,JavaScript代码运行时的 ...

  6. (3) esp8266 官方库文件,没有求逆函数

    下载库文件 #include <MatrixMath.h> #define N (2) mtx_type A[N][N]; mtx_type B[N][N]; mtx_type C[N][ ...

  7. jsp之大文件分段上传、断点续传

    1,项目调研 因为需要研究下断点上传的问题.找了很久终于找到一个比较好的项目. 在GoogleCode上面,代码弄下来超级不方便,还是配置hosts才好,把代码重新上传到了github上面. http ...

  8. ssh:no matching host key type found. Their offer: ssh-dss

    最近突然ssh 服务连接出现 no matching host key type found. Their offer: ssh-dss 以前一直没有问题 可能的原因 openssh 服务升级,加密算 ...

  9. JS全局变量是如何工作的?

    JS全局变量是如何工作的? <script> const one = 1; var two = 2; </script> <script> // All scrip ...

  10. 洛谷 P2701 [USACO5.3]巨大的牛棚Big Barn 题解

    P2701 [USACO5.3]巨大的牛棚Big Barn 题目背景 (USACO 5.3.4) 题目描述 农夫约翰想要在他的正方形农场上建造一座正方形大牛棚.他讨厌在他的农场中砍树,想找一个能够让他 ...