LC.P284[顶端迭代器]

方法一:模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 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 next;

public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
this.iterator = iterator;
if (iterator.hasNext()) next = iterator.next();
}

// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
return next;
}

@Override
public Integer next() {
Integer ans = next;
next = iterator.hasNext() ? iterator.next() : null;
return ans;
}

@Override
public boolean hasNext() {
return next != null;
}
}
  • 时间复杂度:$O(1)$
  • 空间复杂度:$O(1)$

进阶

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

class PeekingIterator<E> implements Iterator<E> {

Iterator<E> iterator;
E next;

public PeekingIterator(Iterator<E> iterator) {
// initialize any member here.
this.iterator = iterator;
if (iterator.hasNext()) next = iterator.next();
}

// Returns the next element in the iteration without advancing the iterator.
public E peek() {
return next;
}

@Override
public E next() {
E ans = next;
next = iterator.hasNext() ? iterator.next() : null;
return ans;
}

@Override
public boolean hasNext() {
return next != null;
}
}
  • 时间复杂度:$O(1)$
  • 空间复杂度:$O(1)$