[LeetCode] 284. Peeking Iterator 瞥一眼迭代器

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().


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.

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

Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.

给了一个迭代器Iterator类接口有next(),hasNext()方法,让在此基础上设计实现一个PeekingIterator,有如下函数:

peek():返回下一个元素,但指针不移动到下一个
next(): 移动到下一个元素x并返回x
hasNext() :返回有下一个元素

解法:为了能peek()后下次next()还得到同样的数字,要用一个缓存保存下一个数字。当peek()时,返回缓存里的数就行,迭代器位置不会变。当next()的时候除了要返回数字和指针移动一位,还要将缓存更新为下一个数字,如果没有下一个就将缓存更新为null。

Java:

class PeekingIterator implements Iterator<Integer> {
    private Iterator<Integer> iter;
    private Integer nextElement;
    private boolean peekUsed;
    
    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        iter = iterator;
    }

    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        if(!peekUsed) {
            nextElement = iter.next();
            peekUsed = true;
        }    
        return nextElement;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        if(peekUsed) {
            peekUsed = false;
            return nextElement;
        }
        return iter.next();
    }

    @Override
    public boolean hasNext() {
        if(peekUsed) {
            return true;
        }
        return iter.hasNext();
    }
}

Java:  用Integer来做global variable, 不用使用boolean

// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
    private Iterator<Integer> iter;
    private Integer next;
    
    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        iter = iterator;
        if (iter.hasNext()) {
            next = iter.next();
        }
    }

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

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

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

Python:

class PeekingIterator(object):
    def __init__(self, iterator):
        """
        Initialize your data structure here.
        :type iterator: Iterator
        """
        self.iterator = iterator
        self.val_ = None
        self.has_next_ = iterator.hasNext()
        self.has_peeked_ = False
        

    def peek(self):
        """
        Returns the next element in the iteration without advancing the iterator.
        :rtype: int
        """
        if not self.has_peeked_:
            self.has_peeked_ = True
            self.val_ = self.iterator.next()
        return self.val_;

    def next(self):
        """
        :rtype: int
        """
        self.val_ = self.peek()
        self.has_peeked_ = False
        self.has_next_ = self.iterator.hasNext()
        return self.val_;

    def hasNext(self):
        """
        :rtype: bool
        """
        return self.has_next_   

C++:

// Below is the interface for Iterator, which is already defined for you.
// **DO NOT** modify the interface for Iterator.
class Iterator {
    struct Data;
    Data* data;
public:
    Iterator(const vector<int>& nums);
    Iterator(const Iterator& iter);
    virtual ~Iterator();
    // Returns the next element in the iteration.
    int next();
    // Returns true if the iteration has more elements.
    bool hasNext() const;
};


class PeekingIterator : public Iterator {
public:
    PeekingIterator(const vector<int>& nums) : Iterator(nums) {
        // Initialize any member here.
        // **DO NOT** save a copy of nums and manipulate it directly.
        // You should only use the Iterator interface methods.
        _flag = false;
    }

    // Returns the next element in the iteration without advancing the iterator.
    int peek() {
        if (!_flag) {
            _value = Iterator::next();
            _flag = true;
        }
        return _value;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    int next() {
        if (!_flag) return Iterator::next();
        _flag = false;
        return _value;
    }

    bool hasNext() const {
        if (_flag) return true;
        if (Iterator::hasNext()) return true;
        return false;
    }
private:
    int _value;
    bool _flag;
};

  

 

All LeetCode Questions List 题目汇总

posted @ 2018-03-28 07:15  轻风舞动  阅读(405)  评论(0编辑  收藏  举报