java - CodeWars算法 Twice linear 问题
伊谢尔伦
伊谢尔伦 2017-04-17 17:33:56
[Java讨论组]

折腾了两天了,一直只是通过测试,但是提交的时候会出错,代码效率太差。求大神指点...
算法如下:
*"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 arrayresult = new ArrayList();
    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 CreateArrayList(ArrayList resultArray)
{
    ArrayList tmp = (ArrayList)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设置的小,那么数组里面的数字也不完整。归根到底,还是代码效率太差...求指导啊

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号