如何解决超出时限的问题? [英] How do I solve the time limit exceeded problem?

查看:143
本文介绍了如何解决超出时限的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好!

我试图编写代码来填充数组中的随机数(使用srand),这样就不会重复任何数字。在执行期间,我收到了超出时间限制的消息。

我该如何解决这个问题?

以下是代码:



  #include   <   iostream  >  
使用 命名空间标准;
#include < cstdlib >
#include < ctime >
int main()
{
srand(time(NULL)) ;
int * deck = new int [ 52 ];
for int i = 0 ; i< 52; i ++)
deck [i] = - 1 ;
int j,top = - 1 ;
while (top!= 51
{
j = rand ()%52;
if (top == - 1
{
top ++ ;
deck [top] = j;
}
else
{
int flag = 0 ,f = 0 ;
while (deck [flag]!= - 1 || flag!= 52
{
if (deck [flag] == j)
f = 1 ;
flag ++;
}
如果(flag == top + 1&& f == 0
{
top ++;
deck [top] = j;
}
}
}
for int k = 0 ; k <52; k ++)
{
cout<< deck [k]<< endl;
}
return 0 ;
}





我的尝试:



我尝试使用printf和scanf而不是cin和cout,因为它们更快但是工作正常。

解决方案

这个循环

 (deck [flag]!=  -  1 || flag!=  52 



将被执行,直到 flag 是52.它类似于

 (flag!=  52 





要在满足第一个条件时离开循环,请使用 AND 操作:

 (deck [flag]!=  -  1 && flag!=  52 


据我记得,数组指向数组的指针不使用相同的语法。我看到了在指针上访问数组元素的语法。



C ++指针 [ ^ ]



你还应该阅读这些书:

The C编程语言 - 维基百科,免费的百科全书 [ ^ ]

https://hassanolity.files.wordpress.com/2013/11/ the_c_programming_language_2.pdf [ ^ ]

http: //www.ime.usp.br/~pf/Kernighan-Ritchie/C-Programming-Ebook.pdf [ ^ ]



C++编程语言 [ ^

Hello!
I was trying to write the code to fill random numbers in an array (using srand) such that no number is repeated. During the execution i got a Time Limit Exceeded message.
How can i solve this?
Following is the code:

#include<iostream>
using namespace std;
#include<cstdlib>
#include<ctime>
int main()
{
	srand(time(NULL));
	int *deck=new int[52];
	for(int i=0;i<52;i++)
		deck[i]=-1;
	int j,top=-1;
	while(top!=51)
	{
		j=rand()%52;
		if(top==-1)
		{
			top++;
			deck[top]=j;
		}
		else
		{
			int flag=0,f=0;
			while(deck[flag]!=-1||flag!=52)
			{
				if(deck[flag]==j)
					f=1;
				flag++;
			}
			if(flag==top+1&&f==0)
			{
				top++;
				deck[top]=j;
			}
		}
	}
	for(int k=0;k<52;k++)
	{
		cout<<deck[k]<<endl;
	}
	return 0;
}



What I have tried:

I tried using printf and scanf instead of cin and cout as they are faster but dint work.

解决方案

This while loop

while(deck[flag]!=-1||flag!=52)


will be executed until flag is 52. It is similar to

while(flag!=52)



To leave the loop when the first condition is met use an AND operation:

while(deck[flag]!=-1 && flag!=52)


As far as I remember, an array an a pointer to an array do not use the same syntax. And I see the syntax to access array elements on a pointer.

C++ Pointers[^]

You should also read these books:
The C Programming Language - Wikipedia, the free encyclopedia[^]
https://hassanolity.files.wordpress.com/2013/11/the_c_programming_language_2.pdf[^]
http://www.ime.usp.br/~pf/Kernighan-Ritchie/C-Programming-Ebook.pdf[^]

C++ Programing Language[^]


这篇关于如何解决超出时限的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆