How to find if a HeapQueue contains a value in Java?

时光总嘲笑我的痴心妄想 提交于 2019-12-24 19:41:05

问题


I am having trouble writing a method with finding if a MaxHeapPriorityQueue contains a value.

The instructions read: The contains(E) method should return true if the given value is found in the queue. It should use its private helper method to search the queue recursively.

Here is what I have so far

public class MaxHeapPriorityQueue<E extends Comparable<E>>
{
private E[] elementData;
private int size;

@SuppressWarnings("unchecked")
public MaxHeapPriorityQueue()
{
    elementData = (E[]) new Comparable[10];
    size = 0;
}
public boolean contains(Object value)
{
     return contains(value, 0);
}
private boolean contains(Object value, int index)
 {
     if(elementData[index] != null && elementData[index] == value)
    {
        return true;
    }
    else
    {
        return contains(value, ++index);
    }
 }
}

回答1:


I don't know why I had such trouble with this, but here is what worked for me. I had to use size instead of elementData.length.

public boolean contains(Object value)
{
    return contains(value, 0);
}
private boolean contains(Object value, int index)
{
    if (index > size)
    {
        return false;
    }
    else if(elementData[index] == value && elementData[index] != null)
    {
        return true;
    }
    else
    {
        return contains(value, ++index);
    }
}



回答2:


Here's another way of solving it.

private boolean contains(Object value, int index)
{
    if(index > size || elementData[index].compareTo((E) value) < 0)
    {
        return false;
    }
    else if(value.equals(elementData[index]))
    {
        return true;
    }
    else
    {
        return contains(value, leftChild(index)) || contains(value, rightChild(index));
    }
}


来源:https://stackoverflow.com/questions/56093410/how-to-find-if-a-heapqueue-contains-a-value-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!