[英]Time limit Exceeded in if-else
Following is a function which change the value of array according to conditions:以下是根据条件更改数组值的 function:
Code:代码:
vector<int> gradingStudents(vector<int> grades) {
int n = grades.size();
int i = 0;
while(i<n)
{
if(grades.at(i)<38)
{
i++;
}
else if( (grades.at(i)+1) % 5==0 )
{
grades.at(i) += 1;
i++;
}
else if( (grades.at(i)+2) % 5 == 0 && grades.at(i)>=38)
{
grades.at(i) += 2 ;
i++;
}
}
return grades;
}
Hackerrank site saying " Time Limit Exceeded". Hackerrank 网站说“超过时间限制”。 I don't understand how can time limit exceeded when there is no loop (except the essential while loop).我不明白没有循环时如何超过时间限制(除了必要的 while 循环)。 If I remove i++
from each if statement and put it outside all if statements then its working fine, but the no.如果我从每个 if 语句中删除i++
并将其放在所有 if 语句之外,那么它可以正常工作,但是不行。 of statements remain same.的语句保持不变。 please help me out请帮帮我
Your code only increments i
when one of the conditions is met.您的代码仅在满足其中一个条件时才增加i
。 It is not clear why you are doing this, because no matter what case the number i
is, in the next iteration you want to check the next number not i
again.目前尚不清楚您为什么要这样做,因为无论数字i
是什么情况,在下一次迭代中,您都想再次检查下一个数字而不是i
。 Your conditions are not complete, in the sense that for example i=42
does not match any condition.您的条件不完整,例如i=42
不匹配任何条件。 Hence, your loop will get stuck once it encounters the first such number.因此,一旦遇到第一个这样的数字,您的循环就会卡住。
Your current issue of an potentially infinte loop can be solved via您当前的潜在无限循环问题可以通过以下方式解决
while(i<n)
{
if(grades.at(i)<38)
{
}
else if( (grades.at(i)+1) % 5==0 )
{
grades.at(i) += 1;
}
else if( (grades.at(i)+2) % 5 == 0)
{
grades.at(i) += 2 ;
}
i++;
}
Or the equivalent for loop.或等效的 for 循环。
Time Limit Exceeded
happens most often when the input size if very large, and/ or your logic takes a long time to process. Time Limit Exceeded
最常发生在输入大小非常大和/或您的逻辑需要很长时间来处理时。 One place I see in your code is, if there was a place where no if
statements were satisfied, it will never be because i
wont be incremented.我在您的代码中看到的一个地方是,如果有一个地方没有满足if
语句,那将永远不会,因为i
不会增加。 Basically your loop will run forever.基本上你的循环将永远运行。
You can either increment i
in the end of the while
loop (because anyway you will increment it),您可以在while
循环结束时增加i
(因为无论如何您都会增加它),
while(i<n)
{
if(grades.at(i)<38)
{
}
else if( (grades.at(i)+1) % 5==0 )
grades.at(i) += 1;
else if( (grades.at(i)+2) % 5 == 0)
grades.at(i) += 2;
i++;
}
Or use a for
loop,或者使用for
循环,
for(int i = 0; i < n; i++)
{
if(grades.at(i)<38)
{
}
else if( (grades.at(i)+1) % 5==0 )
grades.at(i) += 1;
else if( (grades.at(i)+2) % 5 == 0)
grades.at(i) += 2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.