折腾了两天了,一直只是通过测试,但是提交的时候会出错,代码效率太差。求大神指点...
算法如下:
*"Consider a sequence u where u is defined as follows:
The number u(0) = 1 is the first one in u.
For each x in u, then y = 2 x + 1 and z = 3 x + 1 must be in u too.
There are no other numbers in u.
Ex: u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]
1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on..."*
我的代码如下`
public static int dblLinear(int n)
{
ArrayList<Long> arrayresult = new ArrayList<Long>();
arrayresult.add((long) 1);
//循环,生成这样的u[]数组。但是i太大的话,会超时
for (int i = 1; i <= 15; i++)
{
arrayresult = CreateArrayList(arrayresult);
}
System.out.println(arrayresult.toString());
long location = arrayresult.get(n);
return (int)location;
}
public static ArrayList<Long> CreateArrayList(ArrayList<Long> resultArray)
{
ArrayList<Long> tmp = (ArrayList<Long>)resultArray.clone();
for (long single : resultArray)
{
//按照规则,生成y和z。
long y = single * 2 + 1;
long z = single * 3 + 1;
//看看y和z在不在数组里面,不在的话,添加进去。
if (resultArray.indexOf(y) == -1)
{
tmp.add(y);
}
if (resultArray.indexOf(z) == -1)
{
tmp.add(z);
}
}
Collections.sort(tmp);
return tmp;
}
public static void main(String[] args)
{
System.out.println(DoubleLinear.dblLinear(100));
}`
提示错误:"Process was terminated. It took longer than 10000ms to complete
0 Passed"
如果循环的i设置的小,那么数组里面的数字也不完整。归根到底,还是代码效率太差...求指导啊
蝴蝶刀刀
相关分类