엔지니어 게시판
LeetCode 솔루션 분류

284. Peeking Iterator

컨텐츠 정보

본문

[LeetCode 시즌 3] 2022년 4월 24일 문제입니다.

https://leetcode.com/problems/peeking-iterator/


[Medium] 284. 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.

 

Example 1:

Input
["PeekingIterator", "next", "peek", "next", "next", "hasNext"]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 2, 2, 3, false]

Explanation
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]
peekingIterator.next();    // return 1, the pointer moves to the next element [1,2,3].
peekingIterator.peek();    // return 2, the pointer does not move [1,2,3].
peekingIterator.next();    // return 2, the pointer moves to the next element [1,2,3]
peekingIterator.next();    // return 3, the pointer moves to the next element [1,2,3]
peekingIterator.hasNext(); // return False

 

Constraints:

  • 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 nexthasNext, and peek.

 

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

관련자료

댓글 2

mingki님의 댓글

  • 익명
  • 작성일
C++
Runtime: 4 ms, faster than 58.32% of C++ online submissions for Peeking Iterator.
Memory Usage: 7.5 MB, less than 72.34% of C++ online submissions for Peeking Iterator.
class PeekingIterator : public Iterator {
    vector<int> arr;
    int idx;
    
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.
	    arr = vector<int>(nums.begin(), nums.end());
        idx = -1;
	}
	
    // Returns the next element in the iteration without advancing the iterator.
	int peek() {
        return arr[idx + 1];
	}
	
	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	int next() {
	    return arr[++idx];
	}
	
	bool hasNext() const {
	    return idx + 1 < arr.size();
	}
};

austin님의 댓글

  • 익명
  • 작성일
문제 설명에 나와있는 대로 nums를 복사하지 않은(using only constant space) 풀이 입니다.
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.
	    if ((bNext = Iterator::hasNext())) cur = Iterator::next();
	}
	
    // Returns the next element in the iteration without advancing the iterator.
	int peek() {
        return cur;        
	}
	
	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	int next() {
	    auto ret = cur;
        if ((bNext = Iterator::hasNext())) cur = Iterator::next();
        return ret;
	}
	
	bool hasNext() const {
	    return bNext;
	}
    int cur;
    bool bNext;
};
전체 405 / 16 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 543 명
  • 오늘 방문자 4,315 명
  • 어제 방문자 7,414 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,544 명
알림 0