边工作边刷题:70天一遍leetcode: day 56-1
Peeking Iterator
要点:想成cache会比较容易理解,要进一步要考虑什么时候put to cache和什么时候invalidate cache,
- put to cache:peek的时候,如果没在cache中,因为iterator已经移动,直到下一次next,都要在cache中找。
- invalidate cache:next的时候如果在cache中,返回cache同时要invalidate,因为之后无论call peek or next都是要找到当前的下一个值,当前值没用了。
错误点:
- 在peek里call了2次iterator.next(),put to cache的时候call一次就够了
# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator(object):
# def __init__(self, nums):
# """
# Initializes an iterator object to the beginning of a list.
# :type nums: List[int]
# """
#
# def hasNext(self):
# """
# Returns true if the iteration has more elements.
# :rtype: bool
# """
#
# def next(self):
# """
# Returns the next element in the iteration.
# :rtype: int
# """
class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = iterator
self.cache = None
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if not self.cache:
self.cache = self.iterator.next()
# self.iterator.next()
return self.cache
def next(self):
"""
:rtype: int
"""
if self.cache:
ret = self.cache
self.cache = None
return ret
return self.iterator.next()
def hasNext(self):
"""
:rtype: bool
"""
return self.cache is not None or self.iterator.hasNext()
# Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
# val = iter.peek() # Get the next element but not advance the iterator.
# iter.next() # Should return the same value as [val].