작심삼일

[LeetCode] 284 | Peeking Iterator | Python 본문

스터디/코테

[LeetCode] 284 | Peeking Iterator | Python

yun_s 2022. 4. 25. 10:37
728x90
반응형

문제 링크: https://leetcode.com/problems/peeking-iterator/


문제

Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations.

Implement the PeekingIterator class:

  • PeekingIterator(Iterator<int> nums) Initializes the object with the given integer iterator iterator.
  • int next() Returns the next element in the array and moves the pointer to the next element.
  • boolean hasNext() Returns true if there are still elements in the array.
  • int peek() Returns the next element in the array without moving the pointer.

Note: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions.


조건

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 1000
  • All the calls to next and peek are valid.
  • At most 1000 calls will be made to next, hasNext, and peek.

내 풀이

파이썬에서 기본으로 제공하는 Iterator를 사용한다.

현재 self.cur에 현재 value를 저장하고, peek함수가 호출될 때는 self.cur를 리턴, next함수가 호출될 때는 self.cur를 업데이트하고 리턴한다.

hasNext 함수도 self.cur 함수를 이용해서 만든다.


코드

# 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.iter = iterator
        self.cur = self.iter.next() if self.iter.hasNext() else None
        

    def peek(self):
        return self.cur
        

    def next(self):
        nextVal = self.cur
        self.cur = self.iter.next() if self.iter.hasNext() else None
        return nextVal
        

    def hasNext(self):
        return True if self.cur else False
        

# 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].
728x90
반응형
Comments