本文主要是介绍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<List<Integer>> vec2d) 的参数为全局参数
2,抽出2个list的对应的index,如List.get(listIdx).get(elemIdx++)
int listIdx;代表外层list的索引 int elemIdx;代表内层list的索引
public class Vector2D {List<List<Integer>> listOfList;
这篇关于LeetCode 251:展开二维向量的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!