【问题标题】:How to find if a HeapQueue contains a value in Java?如何查找 HeapQueue 是否包含 Java 中的值?
【发布时间】:2019-09-29 07:06:39
【问题描述】:

我在编写查找 MaxHeapPriorityQueue 是否包含值的方法时遇到问题。

说明如下:如果在队列中找到给定值,则 contains(E) 方法应返回 true。它应该使用它的私有辅助方法递归地搜索队列。

这是我目前所拥有的

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);
    }
 }
}

【问题讨论】:

标签: java recursion queue heap priority-queue


【解决方案1】:

我不知道为什么我会遇到这样的麻烦,但这对我有用。我不得不使用 size 而不是 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】:

    这是另一种解决方法。

    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));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-02
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 2019-04-06
      • 1970-01-01
      • 2018-06-12
      相关资源
      最近更新 更多