成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

【LC總結(jié)】Iterator題目<Zigzag 1&2><BST>&

WelliJhon / 2963人閱讀

摘要:方法直接查找數(shù)組的位的迭代器,調(diào)用方法得到的整數(shù)即為要返回的元素。再寫迭代器的方法返回指針元素的并讓指針通過遞歸方法指向下一個元素。

Zigzag Iterator Problem

Given two 1d vectors, implement an iterator to return their elements alternately.

Example

Given two 1d vectors:

v1 = [1, 2]
v2 = [3, 4, 5, 6]

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6].

Note

兩個一維向量,所以建立兩個Iterator。
要實現(xiàn)Zigzag交替迭代,可以用一個奇偶計數(shù)器count進行標(biāo)記。
初始化:對兩個向量v1,v2調(diào)用iterator()方法,分別初始化為it1和it2;并將計數(shù)器置0.
next()方法:每次調(diào)用時先將計數(shù)器+1,若count為奇數(shù)或it2已迭代完,返回it1.next();若count為偶數(shù)且it1已迭代完,返回it2.next()。 default返回-1。
hasNext()方法:只要it1或it2還有未迭代的元素,則返回true。

Solution
import java.util.Iterator;
public class ZigzagIterator {
    private Iterator it1;
    private Iterator it2;
    private int count;
    public ZigzagIterator(List v1, List v2) {
        this.it1 = v1.iterator();
        this.it2 = v2.iterator();
        count = 0;
    }

    public int next() {
        count++;
        if ((count % 2 == 1 && it1.hasNext()) || !it2.hasNext()) return it1.next();
        else if ((count % 2 == 0 && it2.hasNext()) || !it1.hasNext()) return it2.next();
        return -1;
    }

    public boolean hasNext() {
        return it1.hasNext() || it2.hasNext();
    }
}
Zigzag Iterator II Problem

Follow up Zigzag Iterator: What if you are given k 1d vectors? How well can your code be extended to such cases? The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic".

Example

Given k = 3 1d vectors:

[1,2,3]
[4,5,6,7]
[8,9]

Return [1,4,8,2,5,9,3,6,7].

Note

對多個一維向量進行交叉的迭代操作,建立一個迭代器數(shù)組its和一個計位器index。
初始化:將迭代器數(shù)組初始化為ArrayList<>(),再將向量數(shù)組vecs循環(huán)使用迭代器并加入迭代器數(shù)組,然后將計位器初值設(shè)為0。
hasNext()方法:只要迭代器數(shù)組its.size()大于0,就返回true。
next()方法:直接查找its數(shù)組的index位的迭代器,調(diào)用next()方法得到的整數(shù)it即為要返回的元素。不過,找到it之后要先更新index:若當(dāng)前迭代器不為空,index進行先+1后對its.size()取余的操作,指向下一個迭代器;若當(dāng)前迭代器為空,從迭代器數(shù)組中remove這個迭代器,并對index進行對its.size()取余,刷新下個迭代器的位置。更新index后,返回取出的元素it。

Solution
public class ZigzagIterator2 {
    List> its;
    int index;
    public ZigzagIterator2(ArrayList> vecs) {
        this.its = new ArrayList>();
        //遍歷數(shù)組加入迭代器數(shù)組
        for (ArrayList vec: vecs) {
            if (vec.size() > 0) its.add(vec.iterator());
        }
        index = 0;
    }

    public int next() {
        int it = its.get(index).next();
        //刷新指針位置
        if (its.get(index).hasNext()) index = (index+1) % its.size();
        else {
            its.remove(index);
            if (its.size() > 0) index = index % its.size(); //注意這里要判斷its.size()不為0,才能取模
        }
        
        return it;
    }

    public boolean hasNext() {
        return its.size() > 0;
    }
}
Binary Search Tree Iterator Problem

Design an iterator over a binary search tree with the following rules:

Elements are visited in ascending order (i.e. an in-order traversal)
next() and hasNext() queries run in O(1) time in average.

Example

For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]

   10
 /    
1      11
        
  6       12
Challenge

Extra memory usage O(h), h is the height of the tree.

Super Star: Extra memory usage O(1)

Note

用stack對BST進行初始化:查找并加入所有左子樹結(jié)點。
next()方法:對stack.pop()的當(dāng)前結(jié)點cur操作,存為temp,然后對cur.right進行查找左子樹結(jié)點并壓入stack的操作,最后返回原結(jié)點temp。
hasNext()方法:stack非空,則為true。

Solution
public class BSTIterator {
    Stack stack;
    public BSTIterator(TreeNode root) {
        stack = new Stack();
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
    }

    public boolean hasNext() {
        return !stack.isEmpty();
    }
    
    public TreeNode next() {
        TreeNode cur = stack.pop();
        TreeNode temp = cur;
        if (cur.right != null) {
            cur = cur.right;
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
        }
        return temp;
    }
}
Flatten Nested List Iterator Problem

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example

Given the list [[1,1],2,[1,1]], By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Given the list [1,[4,[6]]], By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].

Note

建立此種數(shù)據(jù)類型的迭代器iterator,和它的指針peek(初值為null)。
首先,要進行迭代的數(shù)據(jù)類型為NestedInteger,其實是一個樹狀的層級結(jié)構(gòu),可以用stack+recursion來做。
先寫一個迭代層級結(jié)構(gòu)的遞歸方法iteratorNext():
當(dāng)?shù)鞣强?-hasNext(),取出下一個元素next(),若此元素滿足isInteger(),就返回它;否則將外層的迭代器存入stack,而對當(dāng)前元素繼續(xù)迭代和遞歸。
當(dāng)?shù)鳛榭?-而stack非空,就pop出stack中的元素繼續(xù)遞歸。

再寫迭代器的next()方法:
返回指針元素的getInteger();并讓指針通過遞歸方法指向下一個元素。

hasNext()方法:
指針元素不為空,就返回true。

Solution
import java.util.Iterator;
public class NestedIterator implements Iterator {
    private NestedInteger peek = null;
    private Iterator iterator;
    private Stack> stack = new Stack<>();
    public NestedIterator(List nestedList) {
        iterator = nestedList.iterator();
        peek = iteratorNext();
    }
    public NestedInteger iteratorNext() {
        if (iterator.hasNext()) {
            NestedInteger i = iterator.next();
            if (i.isInteger()) return i;
            else {
                stack.add(iterator);
                iterator = i.getList().iterator();
                return iteratorNext();
            }
        }
        else if (!stack.isEmpty()) {
            iterator = stack.pop();
            return iteratorNext();
        }
        else return null;
    }
    
    @Override
    public Integer next() {
        Integer next = peek.getInteger();
        peek = iteratorNext();
        return next;
    }
    
    @Override
    public boolean hasNext() {
        return peek != null;
    }
    
    @Override
    public void remove() {}
}
Peeking Iterator Problem

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation -- it essentially peek() at the element that will be returned by the next call to next().

Example

Here is an example. Assume that the iterator is initialized to the beginning of the list: [1, 2, 3].

Call next() gets you 1, the first element in the list.

Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.

You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false.

Hint

Think of "looking ahead". You want to cache the next element.
Is one variable sufficient? Why or why not?
Test your design with call order of peek() before next() vs next() before peek().
For a clean implementation, check out Google"s guava library source code.

Follow up

How would you extend your design to be generic and work with all types, not just integer?

Note

略。

Solution
class PeekingIterator implements Iterator {
    public Iterator it;
    public Integer peek;
    public PeekingIterator(Iterator iterator) {
        // initialize any member here.
        this.it = iterator;
        if (it.hasNext()) peek = it.next();
        
    }

    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        return peek;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        Integer res = peek;
        peek = it.hasNext() ? it.next() : null;
        return res;
    }

    @Override
    public boolean hasNext() {
        return peek != null;
    }
}

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/66037.html

相關(guān)文章

  • 解析ES6變量賦值和基本數(shù)據(jù)類型

      let和const  let和const兩者并不存在變量提升  這里要說明的是變量一定要在聲明后使用,否則報錯?! ara=[];   for(vari=0;i<10;i++){   a[i]=function(){   console.log(i);   };   }   a[6]();//10  變量i是var聲明的,我們要知道這里在全局范圍內(nèi)都有效。我們要知道在每一次循環(huán)中,新的...

    3403771864 評論0 收藏0
  • Python必考五大面試題是什么?下文給大家解答

      小編寫這篇文章的一個主要目的,主要是來給大家做個介紹,介紹的內(nèi)容主要是涉及到Python一些試題的講解,小編給大家總結(jié)出來了五道必考的題目,大家可要仔細閱讀哦,下面就給大家詳細解答?! ?、使用while循環(huán)實現(xiàn)輸出2-3+4-5+6...+100的和  #方法一   #從2開始計算   i=2   #定義一個變量用于保存結(jié)果   sum=0   whilei&lt;=100:   i...

    89542767 評論0 收藏0
  • 一文讓你快速了解JavaScript棧

      這篇文章為大家介紹棧(Stack)?! ∈裁词菞??  棧全稱為堆棧,簡單來說就一種數(shù)據(jù),特點是先進后出。在棧中只有兩種基本操作,插入-入棧和刪除-出站,記住棧只有一端可以進行入棧和出棧操作,我們將其稱為棧頂,另一端稱其為棧底;如下圖展示了棧這個數(shù)據(jù)結(jié)構(gòu):  JavaScript中的?! ∑鋵岼avaScript的棧并沒有數(shù)據(jù)類型,需要數(shù)組進行模擬,其中要知道的就是提供的push()和pop()...

    3403771864 評論0 收藏0
  • 展示JS前端面試數(shù)組扁平化手寫flat函數(shù)

      我們現(xiàn)在來說說怎么寫一下數(shù)組扁平化flat(),怎么樣?簡單說題目就是數(shù)組扁平化(也可以叫做手動封裝flat()方法),如何寫好那?  按照不同的星級進行打分: 五星打分制  滿分: ?????  題目實現(xiàn)扁平化的方法 封裝 flatten  題目描述:  有多級嵌套數(shù)組 :[1, [2, [3, [4, 5]]], 6]將其扁平化處理 輸出:[1,2,3,4,5,6]  什么是扁平化  定義...

    3403771864 評論0 收藏0

發(fā)表評論

0條評論

WelliJhon

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<