简体   繁体   English

在JAVA中的FIFO队列中计算PeekMedian()

[英]TO calculate PeekMedian() in a FIFO queue in JAVA

Need help ASAP. 尽快需要帮助。 I want to implement a peekMedian function which looks at the object which has the median value among all the objects without removing it from the queue. 我想实现一个peekMedian函数,该函数查看所有对象中具有中间值的对象,而不将其从队列中删除。 It should return the object which has value of ( size/2 + 1) th lowest. 它应返回值最低(size / 2 + 1)的对象。

for eg. 例如 suppose a queue has the following values. 假设队列具有以下值。 { 2, 1, 2, 2, 6, 4, 2, 5} then the method should return 2 and doesn't remove the object. {2,1,2,2,6,4,2,5},则该方法应返回2并且不删除该对象。

I have tried using collection.sort() but the queue should not be sorted according to the question. 我尝试使用collection.sort(),但不应根据问题对队列进行排序。 I have also tried to copy queue elements in an array and find the nth lowest value and return the value. 我也尝试过复制数组中的队列元素并找到第n个最低值并返回该值。 But the question says " return the object ". 但是问题说“返回对象”。 .. and also the solution should have a less complexity. ..并且解决方案应该具有较少的复杂性。

This looks like a homework, so I'll post an algorithm to solve the problem: 这看起来像是一项家庭作业,因此我将发布一种算法来解决该问题:

  1. Create an new queue that will help you as an auxiliar collection for your objects. 创建一个新队列,该队列将帮助您作为对象的辅助集合。
  2. Start dequeuing the objects from the initial queue and queuing them in the auxuliar queue. 开始从初始队列中将对象出队,并在辅助队列中对其进行排队。
  3. If you know the original size of the queue, when you get to the (size/2 + 1)nth element, use an auxiliar object to keep a copy of its value. 如果知道队列的原始大小,则当到达(size / 2 + 1)nth元素时,请使用辅助对象保留其值的副本。
  4. Continue with the process in step 2. 继续执行步骤2中的过程。
  5. If you can, replace your queue with your auxiliar queue, else repeat the process in pass 2 from the auxiliar queue to the original. 如果可以,将您的队列替换为您的辅助队列,否则重复第2遍中从辅助队列到原始队列的过程。
  6. Return the auxiliar object with the value of the median. 返回带有中间值的辅助对象。

By the way, I think you have a different concept of the median . 顺便说一句,我认为您对中位数有不同的概念。 Or maybe that's how the problem is proposed. 也许这就是提出问题的方式。

Note: If your assignment is to do this without removing any of the objects in the queue, then its impossible, at least that you threat your queue as an Array or a LinkedList and iterate over it. 注意:如果您的任务是在不删除队列中任何对象的情况下执行此操作,则这是不可能的,至少是威胁您将队列作为Array或LinkedList并对其进行迭代。


I'll show you an implementation of the code using Java Queue. 我将向您展示使用Java Queue的代码实现。

public <T> T peekMedian(Queue<T> queue) {
    int medianIndex = queue.size() / 2 + 1; //based on your question.
    Queue<T> auxQueue = new LinkedList<T>();
    T result;
    int count = 1;
    while(queue.peek() != null) {
        auxQueue.add(queue.pop());
        if (count == medianIndex) {
            result = auxQueue.peek();
        }
        count++;
    }
    while(auxQueue.peek() != null) {
        queue.add(auxQueue.pop());
    }
    return result;
}

try this 尝试这个

        import java.util.ArrayDeque;
        import java.util.Iterator;

        public class ArrayDequeDemo {
           public static void main(String[] args) {

        ArrayDeque<Integer> que = new ArrayDeque<Integer>();
            // add elements in queue
              que.add(2);
             que.add(1);
              que.add(2);
              que.add(2);
              que.add(6);
              que.add(4);
              que.add(2);
              que.add(5);

    Integer median = peekMedian(que);

     System.out.println(median);
       }


  private static Integer peekMedian(ArrayDeque<Integer> que){

    Integer ele=0;      //required number
   int size=que.size();  

   //finding the index of ele.
   int elementFromlastIndex= (size/2)+1;


   Iterator descItr = que.descendingIterator();

    int counter=0;  


// iterate in reverse order  till the index of ele is not reached.The loop will break when  when index of ele is reached and thereby finding required element. 

    while(descItr.hasNext() && counter!=elementFromlastIndex) {
             ele =( Integer)descItr.next();
            ++counter;

         if(counter==elementFromlastIndex)
          break;
}//while  
      return ele;       

   }
   }  
        }//class

I think I know how to do, I was asked to implement yesterday. 我想我知道该怎么办,昨天我被要求执行。

It easy to implement max or min in O(1) time, isn't it? 在O(1)时间内实现最大值或最小值很容易,不是吗? Why don't you divide the queue into two queues, one store the item smaller than median, one store the item bigger than median, always keep this relation,and when you insert items, in turns insert to each queue,than you can get the median. 为什么不将队列分成两个队列,一个存储小于中值的项目,一个存储大于中值的项目,始终保持这种关系,当您插入项目时,依次插入每个队列中,您将得到中位数。

There maybe some operating when keep the relation, but I think totally it will be O(1) time because we get max or min in O(1) and inset can be down in O(1), so it's still O(1), sounds good. 保持关系时可能需要进行一些操作,但我认为总共将是O(1)时间,因为我们在O(1)中获得最大值或最小值,而inset在O(1)中可能下降,因此仍为O(1) , 听起来不错。

I hope I was right. 我希望我是对的。 If there's something wrong, please tell me. 如果有什么问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM