281. Zigzag Iterator
Description
Given two vectors of integers v1
and v2
, implement an iterator to return their elements alternately.
Implement the ZigzagIterator
class:
ZigzagIterator(List
initializes the object with the two vectorsv1, List v2) v1
andv2
.boolean hasNext()
returnstrue
if the iterator still has elements, andfalse
otherwise.int next()
returns the current element of the iterator and moves the iterator to the next element.
Example 1:
1 | Input: v1 = [1,2], v2 = [3,4,5,6] |
Example 2:
1 | Input: v1 = [1], v2 = [] |
Example 3:
1 | Input: v1 = [], v2 = [1] |
Constraints:
0 <= v1.length, v2.length <= 1000
1 <= v1.length + v2.length <= 2000
-2^31 <= v1[i], v2[i] <= 2^31 - 1
Follow up: What if you are given k
vectors? How well can your code be extended to such cases?
Clarification for the follow-up question:
The “Zigzag” order is not clearly defined and is ambiguous for k > 2
cases. If “Zigzag” does not look right to you, replace “Zigzag” with “Cyclic”.
Follow-up Example:
1 | Input: v1 = [1,2,3], v2 = [4,5,6,7], v3 = [8,9] |
Hints/Notes
- 2025/05/04 Q1
- queue
- Leetcode solution
Solution
Language: C++
1 | class ZigzagIterator { |