728x90
반응형
이게 왜 미디엄..? 이라는 생각이 들정도로 다른 것들이랑 차이가 많이 나는 문제이다.
솔직히 풀이랄것도 없다. 그냥 맨 위 값을 캐싱하면 해결된다.
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
Iterator<Integer> iterator;
Integer cache;
public PeekingIterator(Iterator<Integer> iterator) {
this.iterator = iterator;
cache = iterator.next();
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
return cache;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
// 맨 위 값을 보관해두고 보내준다.
if(cache == null) {
cache = iterator.next();
return cache;
} else {
// 캐시 값이 있다면? 바꿔주고 보내준다.
int returner = cache;
// 다음 값이 있다면 그 값을 저장하고 보내주기.
if(iterator.hasNext()) {
cache = iterator.next();
} else {
cache = null; // 없으면 null
}
return returner;
}
}
@Override
public boolean hasNext() {
return null != cache;
}
}반응형
'알고리즘 공부' 카테고리의 다른 글
| 304. Range Sum Query 2D - Immutable Java 풀이 (0) | 2026.08.02 |
|---|---|
| 211. Design Add and Search Words Data Structure java 풀이 (0) | 2026.08.02 |
| 208. Implement Trie (Prefix Tree) (0) | 2026.08.02 |
| LeetCode - 173. Binary Search Tree Iterator java 풀이 (0) | 2026.08.02 |
| LeetCode - LRU Cache java 문제풀이 (0) | 2026.08.02 |