簡體   English   中英

是什么使三端隊列的Java鏈表實現緩慢?

[英]What makes the Java linked-list implementation of a triple-ended queue slow?

我正在解決Kattis問題Teque,並且只需執行四個操作即可實現teque(三端隊列):向前推送,向后推送,向中間推送(中間)並讀取索引處的項目。 這項工作的重點是時間復雜度,因此我使用了帶尾鏈表,可以輕松地在正面和背面添加元素。

對於“推入中間”功能,我沒有在列表中調用size(),而是在Teque中存儲了一個類變量以跟蹤列表中的元素數。 這啟用了非常快速的查找。

class Teque {
    public TailedLinkedList list;
    public Kattio io = new Kattio(System.in, System.out);
    public int numItems;

    public Teque() {
        this.list = new TailedLinkedList();
        this.numItems = 0;
    }

    public void push_back(int x) {
        numItems++;
        list.addBack(x);
    }

    public void push_front(int x) {
        numItems++;
        list.addFront(x);
    }

    public void push_middle(int x) {

        int median = (numItems + 1) / 2;
        list.addAtIndex(median, x);
        numItems++;
    }

    public int get(int i) {
        int result = list.getItemAtIndex(i);
        io.println(result);
        io.flush();
        return result;
    }
}

TailedLinkedList的實現:

import java.util.*;

class TailedLinkedList implements ListInterface {
    // attributes
    public ListNode head;
    public ListNode tail;
    public int num_nodes;

    // interface methods

    // Return true if list is empty; otherwise return false.
    public boolean isEmpty() { return (num_nodes == 0); }

    // Return number of items in list
    public int size() { return num_nodes; }

    // return index of item if item is found in the list, otherwise return -1
    public int indexOf(int item) {
        int index = 0;

        for (ListNode cur = head; cur != null; cur = cur.getNext()) {
            if (cur.getItem() == item) 
                return index;
            else 
                index++;
        }
        return -1;
    }

    // return true if item is in the list false otherwise
    public boolean contains(int item) {
        if (indexOf(item) != -1)
            return true;
        return false;
    }

    // get item at index
    public int getItemAtIndex(int index) {
        int counter = 0;
        int item = 0;

        if (index < 0 || index > size()-1) {
            System.out.println("invalid index");
            System.exit(1);
        }
        if (index == size()-1)
            item = tail.getItem();
        else {
            for (ListNode cur = head; cur != null; cur = cur.getNext()) {
                if (counter == index) {
                    item = cur.getItem();
                    break;
                }
                counter++;
            }
        }
        return item;
    }

    // Return first item
    public int getFirst() { return getItemAtIndex(0); }

    // Return last item
    public int getLast() { return getItemAtIndex(size()-1); }

    // add item at position index, shifting all current items from index onwards to the right by 1 
    // pre: 0 <= index <= size()
    public void  addAtIndex(int index, int item) {
        ListNode cur;
        ListNode newNode = new ListNode(item);

        if (index >= 0 && index <= size()) {
            if (index == 0) // insert in front
                insert(null,newNode);
            else if (index == size()) // insert at the back, don't have to move all the way to the back
                insert(tail,newNode);
            else {
                cur = getNodeAtIndex(index-1); // access node at index-1
                insert(cur,newNode);
            }
        }
        else { // index out of bounds
            System.out.println("invalid index");
            System.exit(1);
        }
    } 

    // Add item to front of list
    public void addFront(int item) { addAtIndex(0,item); }

    // Add item to back of list
    public void addBack(int item) { addAtIndex(size(),item); }

    // remove item at index and return it
    // pre: 0 <= index < size()
    public int removeAtIndex(int index) {
        ListNode cur;
        int item = 0;

        // index within bounds and list is not empty
        if (index >= 0 && index < size() && head != null) {
            if (index == 0) // remove 1st item
                item = remove(null);
            else {
                cur = getNodeAtIndex(index-1); // access node at index-1
                item = remove(cur);
            }
        }
        else { // index out of bounds
            System.out.println("invalid index or list is empty");
            System.exit(1);
        }
        return item;
    }

    // Remove first node of list
    public int removeFront() { return removeAtIndex(0); }

    // Remove last node of list
    public int removeBack() { return removeAtIndex(size()-1); }

    // Print values of nodes in list.
    public void print() {
        if (head == null)
            System.out.println("Nothing to print...");
        else {
            ListNode cur = head;
            System.out.print("List is: " + cur.getItem());
            for (int i=1; i < num_nodes; i++) {
             cur = cur.getNext();
             System.out.print(", " + cur.getItem());
            }
            System.out.println(".");
        }
    }

    // non-interface helper methods
    public ListNode getHead() { return head; }
    public ListNode getTail() { return tail; }

    /* return the ListNode at index */
    public ListNode getNodeAtIndex(int index) {
        int counter = 0;
        ListNode node = null;

        if (index < 0 || index > size()-1) {
            System.out.println("invalid index");
            System.exit(1);
        }
        if (index == size()-1) // return tail if index == size()-1
            return tail;
        for (ListNode cur = head; cur != null; cur = cur.getNext()) {
            if (counter == index) {
                node = cur;
                break;
            }
            counter++;
        }
        return node;
    }

    // insert newNode after the node referenced by cur 
    public void insert(ListNode cur, ListNode n) {
        // insert in front
        if (cur == null) {
            n.setNext(head);
            head = n; // update head
            if (tail == null) // update tail if list originally empty
                tail = head;
        }
        else { // insert anywhere else
            n.setNext(cur.getNext());
            cur.setNext(n);
            if (cur == tail) // update tail if inserted new last item
                tail = tail.getNext();
        }
        num_nodes++;
    }

    // remove the node referenced by cur.next, and return the item in the node 
    // if cur == null, remove the first node 
    public int remove(ListNode cur) {
        int value;

        if (cur == null) { // remove 1st node
            value = head.getItem();
            head = head.getNext(); // update head
            if (num_nodes == 1) // update tail to null if only item in list is removed
                tail = null;
        }
        else { // remove any other node
            value = cur.getNext().getItem();
            cur.setNext(cur.getNext().getNext());
            if (cur.getNext() == null) // update tail if last item is removed
                tail = cur;
        }
        num_nodes--;

        return value;
    }
}

但是,我的代碼仍然用完了(輸入100k行,限制2秒)。 我可以立即改進我的算法嗎? addAtIndexgetItemAtIndex運行時間為O(n)。

push_midle導致遍歷列表的一半。 一種解決方案是使用兩個列表 ,前半部分和后半部分。 如果列表不平衡,請在兩個列表之間移動元素。

(可能只是ListIterator也可能這樣做;盡管對於天真的方法,必須擔心ConcurrentModificationException。)

對Joop Eggen解決方案的修改是使用2個陣列(前陣列用於快速pushFront,后陣列用於快速pushBack)。

  • frontIndex = front.length / 2和front.length之間的任何值-1
  • frontMidIndex = frontIndex-1
  • backIndex = 0到back.length / 2之間的任何值
  • backMidIndex = backIndex + 1

有效內容:front [frontIndex .. frontMidIndex [+ back [backMidIndex .. backIndex [

pushFront:

  • frontIndex> 0?
    • 設置為frontIndex,遞減frontIndex
  • 否則frontMidIndex <front.length
    • 將前數組向后移x,將frontIndex和frontMidIndex增加x,如上設置
  • 其他
    • 將某些部分復制回去或增大數組,然后像上面一樣進行

推回:

  • 對於back,backIndex(<back.length),backMidIndex(> 0),切入/切入和移位方向相同

pushMid(這需要更多思考):

  • 最佳的是前后的有效長度相等或相等。 然后將其設置為frontMidIndex或backMidIndex的集合(類似於上面的邏輯)
  • 如果中值落在兩個數組之一的有效范圍的中間,則可以
    • 在此數組中移動內容以創建元素的位置。
    • 或在兩個數組之間移動內容以調整midIndexes以用於進一步的pushMid。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM