LeetCode 251:展开二维向量

题目

Implement an iterator to flatten a 2d vector.

Example:

[1,2,3,4,5,6]
[1,2,3,4,5,6]
Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.

题解:

用两个index 分别记录list 的 index 和当前 list的element index.

Time Complexity: Vector2D() O(1). hasNext() O(vec2d.size()). next() O(1). Space: O(1).

嵌套list解法:

1,提取 Vector2D(List> vec2d)  的参数为全局参数

2,抽出2个list的对应的index,如List.get(listIdx).get(elemIdx++)

int listIdx;代表外层list的索引
int elemIdx;代表内层list的索引
public class Vector2D {
    List> listOfList;
   

你可能感兴趣的:(算法,Java,leetcode,算法,职场和发展)