Given an array of integers coins, where each el
Constraints
N/A
Example 1
Input:
coins = [3, 4, 6]
Output:
[2, 2, 3]
Explanation: No explanation for now..
解法
经典 LC 441 变体:对每个 n = coins[i],找最大 k 使 k*(k+1)/2 ≤ n。可直接二分或求根公式 k = floor((sqrt(8n+1)-1)/2)。时间复杂度 O(len(coins)),空间复杂度 O(len(coins)) 用于结果数组。
from typing import List
import math
def arrangeCoins(coins: List[int]) -> List[int]:
res = []
for n in coins:
k = int((math.isqrt(8 * n + 1) - 1) // 2)
res.append(k)
return resclass Solution {
int[] arrangeCoins(int[] coins) {
int[] res = new int[coins.length];
for (int i = 0; i < coins.length; i++) {
long n = coins[i];
long k = (long) ((Math.sqrt(8.0 * n + 1) - 1) / 2);
while ((k + 1) * (k + 2) / 2 <= n) k++;
while (k * (k + 1) / 2 > n) k--;
res[i] = (int) k;
}
return res;
}
}class Solution {
public:
vector<int> arrangeCoins(vector<int>& coins) {
vector<int> res;
for (int n : coins) {
long long k = (long long) ((sqrt(8.0 * n + 1) - 1) / 2);
while ((k + 1) * (k + 2) / 2 <= n) k++;
while (k * (k + 1) / 2 > n) k--;
res.push_back((int) k);
}
return res;
}
};At Alarm.com we need a new piece of functionality that will tell us how many days it's been since a user last logged into our site. Our product manager has given us the following requirements that they would like implemented so that we can start tracking inactive users. Minimally Viable Product Input should be a string in the format "MM/dd/yyyy" The input should be converted to a date and subtracted from today's date Return the absolute whole number of days as a string Things to consider If the input does not contain any characters or is only whitespace then return error code "E8430" If the input is in the wrong format return error code "E9021" If the input is in the correct format but not a valid date then return error code "E1756"
Constraints
lastLoginDateis a string up to 10 characters- Format must be
MM/dd/yyyy(or returns error codes)
Example 1
Input:
lastLoginDate = "07/06/2022"
Output:
"1"
Explanation: Input = "07/06/2022" Today = 07/07/2022 Output = "1"
Example 2
Input:
lastLoginDate = "02/30/2020"
Output:
"E1756"
Explanation: The input "02/30/2020" is in the correct format but not a valid date because February does not have 30 days. Therefore, the function returns the error code "E1756". (By Tomtato. If you find it wrong, pls lmk! THX !)
解法
先校验输入:空或全空白返回 "E8430";不符合 MM/dd/yyyy 正则返回 "E9021";用 LocalDate.parse (Java) / datetime.strptime (Python) / 手动校验 (C++) 解析日期,若无效返回 "E1756";否则用 today - parsed 取绝对天数返回字符串。时间复杂度 O(1)。
import re
from datetime import date, datetime
def daysSinceLastLogin(lastLoginDate: str) -> str:
if lastLoginDate is None or lastLoginDate.strip() == "":
return "E8430"
if not re.fullmatch(r"\d{2}/\d{2}/\d{4}", lastLoginDate):
return "E9021"
try:
d = datetime.strptime(lastLoginDate, "%m/%d/%Y").date()
except ValueError:
return "E1756"
return str(abs((date.today() - d).days))import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.time.temporal.ChronoUnit;
class Solution {
String daysSinceLastLogin(String lastLoginDate) {
if (lastLoginDate == null || lastLoginDate.trim().isEmpty()) return "E8430";
if (!lastLoginDate.matches("\\d{2}/\\d{2}/\\d{4}")) return "E9021";
try {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM/dd/uuuu").withResolverStyle(ResolverStyle.STRICT);
LocalDate d = LocalDate.parse(lastLoginDate, fmt);
return String.valueOf(Math.abs(ChronoUnit.DAYS.between(d, LocalDate.now())));
} catch (Exception e) {
return "E1756";
}
}
}#include <regex>
#include <ctime>
class Solution {
public:
string daysSinceLastLogin(string lastLoginDate) {
if (lastLoginDate.empty() || all_of(lastLoginDate.begin(), lastLoginDate.end(), ::isspace)) return "E8430";
if (!regex_match(lastLoginDate, regex("\\d{2}/\\d{2}/\\d{4}"))) return "E9021";
int mm = stoi(lastLoginDate.substr(0, 2));
int dd = stoi(lastLoginDate.substr(3, 2));
int yy = stoi(lastLoginDate.substr(6, 4));
if (mm < 1 || mm > 12 || dd < 1) return "E1756";
int dim[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool leap = (yy % 4 == 0 && yy % 100 != 0) || yy % 400 == 0;
if (mm == 2 && leap) dim[1] = 29;
if (dd > dim[mm - 1]) return "E1756";
tm a{}; a.tm_year = yy - 1900; a.tm_mon = mm - 1; a.tm_mday = dd;
time_t ta = mktime(&a);
time_t now = time(nullptr);
long diff = (long)(difftime(now, ta) / 86400.0);
return to_string(abs(diff));
}
};