【发布时间】:2020-08-07 19:55:40
【问题描述】:
具体问题的链接如下:https://leetcode.com/problems/nth-magical-number/。我的代码显示“超出时间限制”,我无法弄清楚我的代码中的错误到底在哪里。我的代码如下:
class Solution {
public:
typedef unsigned int ull;
int gcd(int A,int B)
{
if(B==0)
return A;
else
return gcd(B,A%B);
}
int nthMagicalNumber(int N, int A, int B) {
ull m;
if(A<B)
{
int t;
t=A;
A=B;
B=t;
}
ull lcm=(A*B)/gcd(A,B);
ull l=2;
ull h=1e9;
ull n;
while(l<=h)
{
m=l+(h-1)/2;
n=(m/A)+(m/B)-(m/lcm);
if(n==N)
break;
else if(n<N)
l=m+1;
else if(n>N)
h=m-1;
}
ull x=(1e9)+7;
return (int)(m%x);
}
};
谁能让我知道我错在哪里以及如何纠正错误?
【问题讨论】:
-
超过时间限制并不一定意味着你的代码有错误。这通常意味着您选择的算法效率不足以在所需的时间内解决问题。
-
超过时间限制几乎总是意味着您的解决方案使用的算法效率不够高,您必须找到更好的算法。你的代码可能有一个可行的算法,但它访问内存的效率很低。
-
关于
typedef unsigned int ull;来自名称ull我本来期望typedef unsigned long long ull;。这是因为像这样令人讨厌的惊喜,您应该更喜欢使用像<cstdint>(these for example) 中的标准类型。它们需要更多的输入,但任何熟悉 C 或 C++ 的人都可以立即理解。 -
你创建这个类有什么原因吗?这些功能可以是独立的。
-
typedef unsigned int ull;- 请不要这样混淆你的代码。
标签: c++ binary-search