摘要:另一个则是的迭代器,它负责记录当前到哪一个的迭代器了。每次时,我们先调用一下,确保当前的迭代器有下一个值。代码当前列表的迭代器为空,或者当前迭代器中没有下一个值时,需要更新为下一个迭代器
Flatten 2D Vector
数组法 复杂度Implement an iterator to flatten a 2d vector.
For example, Given 2d vector =
[ [1,2], [3], [4,5,6] ]By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].
时间 O(N) 空间 O(1)
思路用一个数组表示每个List的迭代器,然后再记录一个变量,用来表示当前用到了第几个迭代器。
代码public class Vector2D {
List> its;
int curr = 0;
public Vector2D(List> vec2d) {
this.its = new ArrayList>();
for(List l : vec2d){
// 只将非空的迭代器加入数组
if(l.size() > 0){
this.its.add(l.iterator());
}
}
}
public int next() {
Integer res = its.get(curr).next();
// 如果该迭代器用完了,换到下一个
if(!its.get(curr).hasNext()){
curr++;
}
return res;
}
public boolean hasNext() {
return curr < its.size() && its.get(curr).hasNext();
}
}
双迭代器法
复杂度
时间 O(N) 空间 O(1)
思路维护两个迭代器:一个是输入的List>的迭代器,它负责遍历List
public class Vector2D {
Iterator> it;
Iterator curr;
public Vector2D(List> vec2d) {
it = vec2d.iterator();
}
public int next() {
hasNext();
return curr.next();
}
public boolean hasNext() {
// 当前列表的迭代器为空,或者当前迭代器中没有下一个值时,需要更新为下一个迭代器
while((curr == null || !curr.hasNext()) && it.hasNext()){
curr = it.next().iterator();
}
return curr != null && curr.hasNext();
}
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/64586.html
摘要:栈法复杂度时间空间思路对于一个根节点,我们将它的右子树压进一个栈中,然后将它的左子树放到右边来。如果该节点没有左子树,说明该节点是某个左子树的最后一个节点,我们这时候把栈中最近的右子树出来接到它的右边。 Flatten Binary Tree to Linked List Given a binary tree, flatten it to a linked list in-plac...
Problem Implement an iterator to flatten a 2d vector. Example: Input: 2d vector = [ [1,2], [3], [4,5,6] ] Output: [1,2,3,4,5,6] Explanation: By calling next repeatedly until hasNext returns fals...
摘要:网络结构来自固定随机数种子以复现结果创建维向量,并扩展维度适应对输入的要求,的大小为定义卷积层卷积核数量为卷积核大小为定义最大化池化层平铺层,调整维度适应全链接层定义全链接层编译模型打印层的输出打印网络结构最终输出如下卷积结果网络结 showImg(https://segmentfault.com/img/remote/1460000012731670); 网络结构来自https://...
摘要:本篇继续学习之路,实现更多的特殊方法以让自定义类的行为跟真正的对象一样。之所以要让向量不可变,是因为我们在计算向量的哈希值时需要用到和的哈希值,如果这两个值可变,那向量的哈希值就能随时变化,这将不是一个可散列的对象。 《流畅的Python》笔记。本篇是面向对象惯用方法的第二篇。前一篇讲的是内置对象的结构和行为,本篇则是自定义对象。本篇继续Python学习之路20,实现更多的特殊方法以让...
阅读 2281·2023-04-25 16:53
阅读 1637·2021-10-13 09:39
阅读 894·2021-09-08 09:35
阅读 1903·2019-08-30 13:03
阅读 2405·2019-08-30 11:06
阅读 2019·2019-08-30 10:59
阅读 3427·2019-08-29 17:00
阅读 2476·2019-08-23 17:55