엿보기 반복자
peek 및 hasNext 연산 외에 기존 반복자에서 next 연산을 지원하는 반복자를 설계합니다.PeekingIterator 클래스를 구현합니다.PeekingIterator(Iterator<int> nums) 주어진 정수 반복자를 사용하여 개체를 초기화합니다iterator. int next() 배열의 다음 요소를 반환하고 포인터를 다음 요소로 이동합니다. boolean hasNext() 배열에 여전히 요소가 있으면 true를 반환합니다. int peek() 포인터를 이동하지 않고 배열의 다음 요소를 반환합니다. 참고: 언어마다 생성자 및
Iterator 의 구현이 다를 수 있지만 모두 int next() 및 boolean hasNext() 함수를 지원합니다.예 1:
입력
["PeekingIterator", "다음", "픽", "다음", "다음", "hasNext"]
[[[1, 2, 3]], [], [], [], [], []]
산출
[널, 1, 2, 2, 3, 거짓]
설명
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]);//[1,2,3]
엿보기Iterator.next();//1을 반환하면 포인터가 다음 요소 [1,2,3]로 이동합니다.
엿보기Iterator.peek();//2를 반환하면 포인터가 이동하지 않습니다 [1,2,3].
엿보기Iterator.next();//2를 반환하면 포인터가 다음 요소 [1,2,3]로 이동합니다.
엿보기Iterator.next();//3을 반환하면 포인터가 다음 요소 [1,2,3]로 이동합니다.
엿보기Iterator.hasNext();//거짓 반환
제약:
1 <= nums.length <= 1000 1 <= nums[i] <= 1000 next 및 peek에 대한 모든 호출이 유효합니다. 1000 호출은 next , hasNext 및 peek 로 이루어집니다. 후속 조치: 설계를 일반화하고 정수뿐만 아니라 모든 유형에서 작동하도록 어떻게 확장하시겠습니까? 해결책:
# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator:
# 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:
def __init__(self, iterator):
self.itr = iterator
self.curr = None
def peek(self):
if self.curr != None:
return self.curr
self.curr = self.itr.next()
return self.curr
def next(self):
if self.curr != None:
val = self.curr
self.curr = None
return val
return self.itr.next()
def hasNext(self):
return self.curr != None or self.itr.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].
Reference
이 문제에 관하여(엿보기 반복자), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/theabbie/peeking-iterator-3f8d텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)