Decode Algorithms & LeetCode
  • Decode Algorithms & LeetCode
  • G家练习
  • Array
    • Two Sum
    • Two Pointers
    • PrefixSum
    • Matrix
    • Interval & Sweepline
    • Sort
    • Iterator
    • Segment Tree
  • Binary Search
    • 教学
    • Binary Search on Matrix
    • Binary Search To Find An Answer
  • String
    • Parenthesis
    • Sliding Window
    • Trie
  • LinkedList
  • Tree
    • Level Order Traversal
    • BST or Inorder
    • Construst Tree
  • Stack
  • Heap
  • Greedy
  • BFS
  • DFS
    • DFS on String
    • Backtracking
    • DFS+Memo
  • Graph
    • Union Find
    • Topological Sort
    • Dijkstra
    • Bipartite Graph
  • Dynamic Programing
    • DP on String
    • Knapsack Problem
  • Design
    • Concurrency
  • Math
  • Bit Manipulation
Powered by GitBook
On this page

Was this helpful?

  1. Array

Iterator

PreviousSortNextSegment Tree

Last updated 4 years ago

Was this helpful?

public class ZigzagIterator {
    Queue<Iterator<Integer>> queue = new LinkedList<>();
    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        if (!v1.isEmpty()) queue.offer(v1.iterator());
        if (!v2.isEmpty()) queue.offer(v2.iterator());
    }

    public int next() {
        Iterator<Integer> curt = queue.poll();
        int val = curt.next();
        if (curt.hasNext()) queue.offer(curt);
        return val;
    }

    public boolean hasNext() {
       return !queue.isEmpty();
    }
}

Pre fill a peek element.

class PeekingIterator implements Iterator<Integer> {
    Integer e;
    Iterator<Integer> iterator;
	public PeekingIterator(Iterator<Integer> iterator) {
	    // initialize any member here.
	    this.iterator = iterator;
        fillNext();
	}
	
  // Returns the next element in the iteration without advancing the iterator.
	public Integer peek() {
        return e;    
	}
    
  private void fillNext() {
      if (!iterator.hasNext()) {
          e = null;
      } else {
          e = iterator.next();
      }
  }
	
	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	@Override
	public Integer next() {
        if (e == null) return null;
	    int temp = e;
        fillNext();
        return temp;
	}
	
	@Override
	public boolean hasNext() {
	    return e != null;
	}
}
class RLEIterator {
    int i = 0;
    int[] A;
    public RLEIterator(int[] A) {
        this.A = A;
    }
    
    public int next(int n) {
        while (i < A.length && n > A[i]) {
            n -= A[i];
            i += 2;
        }
        if (i >= A.length) return -1;
        A[i] -= n;
        return A[i + 1];
    }
}

281. Zigzag Iterator
284. Peeking Iterator
900. RLE Iterator