codewars:Twice linear

在做算法题,遇到一个小坑,记录一下。

题目:

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...

Task:
Given parameter n the function dbl_linear (or dblLinear...) returns the element u(n) of the ordered (with <) sequence u (so, there are no duplicates).

Example:
dbl_linear(10) should return 22

Note:
Focus attention on efficiency

思路:

固定两个 队列,一个队列存放 2 * x + 1,另外一个队列存放 3 * x + 1
每次取最前面的数进行比较,取出小的那个。再将取出数的对应关系值放到对应队列中。

代码

public class DoubleLinear {

    public static int dblLinear (int n) {
        Queue<Integer> arr1 = new LinkedList<Integer>();
        Queue<Integer> arr2 = new LinkedList<Integer>();
        int temp = 1;
        int ant = 0;
        while(ant<n){
            arr1.offer(2*temp+1);
            arr2.offer(3*temp+1);
            if(arr1.element()==arr2.element()){
                arr2.poll();
                temp = arr1.poll();
            }else{
                temp = arr1.element()<arr2.element()?arr1.poll():arr2.poll();
            }
            ant++;
        }
        return temp;
    }

坑:
上面的代码在运行基础用例的时候是通过的,但是提交上去的n数量级大的话用例就会出错。
https://blog.csdn.net/weixin_39800144/article/details/81165898
最后发现 具体原因 如上 博文所述 👆
代码在比较 Integer对象的时候用了“==”,结果比较的是 对象的地址值。
代码判断语句地方换成

if(arr1.element().equals(arr2.element()))

后通过所有测试用例。
附上 Integer对象 equals()的源码:

    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

以下,摘自原博文:
Integer值的比较有个坑:对于Integer var = ?,在-128至127范围内的赋值, Integer 对象是在IntegerCache.cache 产生,会复用已有对象,这个区间内的 Integer 值可以直接使用==进行判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象;所以,在上面,我们的c和d两个,虽然值是一样的,但是地址不一样。
这是一个大坑,很多人会在项目中使用==来比较Integer!强烈建议,必须使用equals来比较。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,971评论 0 13
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 3,004评论 0 0
  • 一个我 在白昼 脚生了根 梦想在秋风中挣扎 一个我 在夜晚 身生了翼 梦想在星空中闪烁 一个我 在秋天 看树生年轮...
    妮妮雅阅读 254评论 0 3
  • 我连我来自小学二年级一班,的名字叫:韩梦荧,我扎着一个马尾辫,有这一对炯炯有神的小眼睛。 我属虎,老虎身上有一...
    韩梦荧阅读 367评论 0 0
  • quora上的一个回答很简明Suppose you’re using a Convolutional Neural...
    夕宝爸爸阅读 639评论 0 0

友情链接更多精彩内容