在做算法题,遇到一个小坑,记录一下。
题目:
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来比较。