实施一个队列,您可以在其中将元素插入到特定位置,同时在恒定时间内进行入队/出队?

时间:2019-02-20 18:03:03

标签: java algorithm data-structures queue

样本输入:

2
3 101 102 103
3 201 202 203
ENQUEUE 101
ENQUEUE 201
ENQUEUE 102
ENQUEUE 202
ENQUEUE 103
ENQUEUE 203
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
STOP

第一行=“组数”,N

以下N行=第一个数字是K组中元素的数量,随后的K个数字是元素本身(范围为0 ... 999999)

直到STOP输入的所有行= Enqueue或Dequeue查询。如果为Enqueue,则在队列末尾的A.处排队当前正在处理的元素E,如果队列中没有与E或B属于同一“组”的元素。与E属于同一“组”

出队很简单,只需从队列中删除第一个元素即可。对于每个出队查询,输出要出队的元素。

元素的入队和出队只需要恒定时间

输出为:

101
102
103
201
202
203

我最初是在考虑某种2D嵌套结构,例如队列数组之类的东西,但是入队/出队并不会花费固定的时间,所以我不确定。

此外,在查询之前我已经得到了元素本身的事实应该是一个提示,但是对于我不确定的内容。

2 个答案:

答案 0 :(得分:2)

如果组不相交,则每个组中的元素始终聚集在一起。换句话说,您有一个队列队列:

  • 为每个组创建一个(最初为空)队列;
  • 创建一个索引结构,以恒定时间搜索与输入数字相对应的组(暴力解决方案是具有1000000个引用的数组,可以更改为HashSet);
  • 创建队列引用队列(“主”队列)。

现在ENQUEUE X

  • 找到X的相应队列;
  • 在其中添加X;如果为空,则将队列排入主队列。

对于DEQUEUE

  • 采用主队列中的第一个队列,从中取出元素;
  • 如果为空,请从主队列中取出队列。

答案 1 :(得分:0)

假设: 1.一个元素仅属于一组。 2. ENQUEUE查询将包含一组条目的数据。

代码:

public class Queue {
    private static final BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
    private static int noOfGroups = 0;
    private static int totalNumberOfElements = 0;
    private static HashMap<String, Element> elementsMap = new HashMap<String, Element>();
    private static HashMap<Integer, Group> groupsMap = new HashMap<Integer, Group>();
    private static Element queueStart = null;
    private static Element queueEnd = null;

    public static void main(String[] args) throws IOException {
        StringBuffer output = new StringBuffer();
        getInput(InputType.NO_OF_GROUP, null);
        for (int groupId = 0; groupId < noOfGroups; ++groupId) {
            getInput(InputType.GROUP_ENTRY, groupId);
        }
        if (elementsMap.size() != totalNumberOfElements) {
            System.err.println(
                    "Note: Same element found on different groups. Group that entered later will be considered.");
        }
        String query;
        while (!"STOP".equals(query = getInput(InputType.QUERY_ENTRY, null))) {
            if (query.equals("DEQUEUE")) {
                Element element = processDEQUEUE();
                if (element != null) {
                    // output the element that is dequeued.
                    output.append(element.getData()).append(System.lineSeparator());
                }
            } else {
                processENQUEUE(query);
            }
        }
        System.out.println(System.lineSeparator() + "Result:");
        System.out.println(output);

    }

    private static void processENQUEUE(String data) {
        Element currentElement = elementsMap.get(data);
        if (currentElement != null) {

            int groupId = currentElement.getGroupId();
            Group currentGroup = groupsMap.get(groupId);

            if (currentGroup.getLast() == null) {
                // Case A:
                // queuing the element "data" at the end of the queue if there's no
                // element in the queue that belongs to the same "group" as "data"
                currentGroup.setLast(currentElement);
                if (queueStart == null) {
                    queueStart = currentElement;
                }
                if (queueEnd == null) {
                    queueEnd = currentElement;
                } else {
                    queueEnd.setNext(currentElement);
                    queueEnd = currentElement;

                }

            } else if (currentGroup.getLast() != null) {
                // Case B:
                // queuing the element "data" right behind the last element which
                // belongs to the same "group" as "data"
                currentElement.setNext(currentGroup.getLast().getNext());
                currentGroup.getLast().setNext(currentElement);
                currentGroup.setLast(currentElement);

            }

        } else {
            System.err.println("Cannot process enqueue for " + data + ". There is no group that contains this data.");
        }

    }

    private static Element processDEQUEUE() {
        Element element = null;
        // removing the first element from the queue.
        if (queueStart == null) {
            System.err.println("Cannot process dequeue. Queue is empty.");
        } else {
            element = queueStart;
            queueStart = queueStart.getNext();
        }
        return element;
    }

    private static String getInput(InputType inputType, Integer groupId) throws IOException {
        boolean isValidInput = false;
        String input = null;
        String message = null;
        String returnValue = null;
        while (!isValidInput) {
            switch (inputType) {
            case NO_OF_GROUP:
                System.out.println("Number of \"groups\": ");
                break;
            case GROUP_ENTRY:
                System.out.println("Group-" + groupId + " Entry: ");
                break;
            case QUERY_ENTRY:
                System.out.println("Query: ");
            }
            input = BR.readLine();
            switch (inputType) {
            case NO_OF_GROUP:
                try {
                    noOfGroups = Integer.parseInt(input);
                    isValidInput = true;
                } catch (NumberFormatException ex) {
                    message = ex.getMessage();
                    isValidInput = false;
                }
                break;
            case GROUP_ENTRY:
                try {
                    String groupInputElements[] = input.split(" ");
                    int noOfElements = 0;

                    noOfElements = Integer.parseInt(groupInputElements[0]);
                    if (groupInputElements.length != noOfElements + 1) {
                        throw new IllegalArgumentException("Expecting " + noOfElements + " elements. Found "
                                + (groupInputElements.length - 1) + " elements.");
                    }
                    groupsMap.put(groupId, new Group());
                    for (int index = 1; index < groupInputElements.length; ++index) {
                        Element element = new Element();
                        element.setGroupId(groupId);
                        element.setData(groupInputElements[index]);
                        elementsMap.put(groupInputElements[index], element);
                    }
                    totalNumberOfElements += noOfElements;
                    isValidInput = true;
                } catch (IllegalArgumentException ex) {
                    message = ex.getMessage();
                    isValidInput = false;
                }
                break;
            case QUERY_ENTRY:
                try {
                    if (!input.contains("ENQUEUE") && !input.equals("DEQUEUE") && !input.equals("STOP")) {
                        throw new IllegalArgumentException("Query can only be ENQUEUE, DEQUEUE or STOP");
                    } else if (input.contains("ENQUEUE")) {
                        String[] enqueueData = input.split(" ");
                        if (enqueueData.length != 2) {
                            throw new IllegalArgumentException(
                                    "Invalid Data. Expected format: ENQUEUE <DATA>\t\tExample: ENQUEUE 101");
                        }
                        returnValue = enqueueData[1];
                    } else {
                        returnValue = input;
                    }
                    isValidInput = true;
                } catch (IllegalArgumentException ex) {
                    message = ex.getMessage();
                    isValidInput = false;
                }
            }
            if (message != null) {
                System.err.println(message);
                message = null;
            }

        }
        return returnValue;
    }

}

enum InputType {
    NO_OF_GROUP, GROUP_ENTRY, QUERY_ENTRY
}

class Element {
    private Element next;
    private int groupId;
    private String data;

    public Element getNext() {
        return next;
    }

    public void setNext(Element next) {
        this.next = next;
    }

    public int getGroupId() {
        return groupId;
    }

    public void setGroupId(int groupId) {
        this.groupId = groupId;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

class Group {

    public Element getLast() {
        return last;
    }

    public void setLast(Element last) {
        this.last = last;
    }

    private Element last;
}

结果: enter image description here