[LeetCode] 251. 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].
Hint:
- How many variables do you need to keep track?
- Two variables is all you need. Try with
xandy. - Beware of empty rows. It could be the first few rows.
- To write correct code, think about the invariant to maintain. What is it?
- The invariant is
xandymust always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it? - Not sure? Think about how you would implement
hasNext(). Which is more complex? - Common logic in two different places should be refactored into a common method.
Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.
给一个二维向量数组压平输出为一个数组。要实现一个iterator,包括next和hasNext函数。
解法:将二维数组按顺序先存入到一个一维数组里,然后维护一个变量i来记录当前遍历到的位置,hasNext函数看当前坐标是否小于元素总数,next函数即为取出当前位置元素。
Java:one iterator
public class Vector2D {
List<Iterator<Integer>> its;
int curr = 0;
public Vector2D(List<List<Integer>> vec2d) {
this.its = new ArrayList<Iterator<Integer>>();
for(List<Integer> 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();
}
}
Java: two iterator
public class Vector2D {
Iterator<List<Integer>> it;
Iterator<Integer> curr;
public Vector2D(List<List<Integer>> 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();
}
}
Java:
public class Vector2D {
private List<List<Integer>> vec2d;
private int rowId;
private int colId;
private int numRows;
public Vector2D(List<List<Integer>> vec2d) {
this.vec2d = vec2d;
rowId = 0;
colId = 0;
numRows = vec2d.size();
}
public int next() {
int ans = 0;
if (colId < vec2d.get(rowId).size()) {
ans = vec2d.get(rowId).get(colId);
}
colId++;
if (colId == vec2d.get(rowId).size()) {
colId = 0;
rowId++;
}
return ans;
}
public boolean hasNext() {
while (rowId < numRows && (vec2d.get(rowId) == null || vec2d.get(rowId).isEmpty())) {
rowId++;
}
return vec2d != null &&
!vec2d.isEmpty() &&
rowId < numRows;
}
}
Java: Followup: As an added challenge, try to code it using only iterators in C++ or iterators in Java.
public class Vector2D {
private Iterator<List<Integer>>outerIterator;
private Iterator<Integer> innerIterator;
public Vector2D(List<List<Integer>> vec2d) {
outerIterator = vec2d.iterator();
innerIterator = Collections.emptyIterator();
}
public int next() {
return innerIterator.next();
}
public boolean hasNext() {
if (innerIterator.hasNext()) {
return true;
}
if (!outerIterator.hasNext()) {
return false;
}
innerIterator = outerIterator.next().iterator();
return hasNext();
}
}
/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i = new Vector2D(vec2d);
* while (i.hasNext()) v[f()] = i.next();
*/
Python:
class Vector2D(object):
# @param vec2d {List[List[int]]}
def __init__(self, vec2d):
# Initialize your data structure here
self.row, self.col, self.vec2d = 0, 0, vec2d
# @return {int} a next element
def next(self):
# Write your code here
self.col += 1
return self.vec2d[self.row][self.col - 1]
# @return {boolean} true if it has next element
# or false
def hasNext(self):
# Write your code here
while self.row < len(self.vec2d) and \
self.col >= len(self.vec2d[self.row]):
self.row, self.col = self.row + 1, 0
return self.row < len(self.vec2d)
# Your Vector2D object will be instantiated and called as such:
# i, v = Vector2D(vec2d), []
# while i.hasNext(): v.append(i.next())
C++:
class Vector2D {
public:
Vector2D(vector<vector<int>>& vec2d) {
// Initialize your data structure here
begin = vec2d.begin();
end = vec2d.end();
pos = 0;
}
int next() {
// Write your code here
hasNext();
return (*begin)[pos++];
}
bool hasNext() {
// Write your code here
while (begin != end && pos == (*begin).size())
begin++, pos = 0;
return begin != end;
}
private:
vector<vector<int>>::iterator begin, end;
int pos;
};
/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i(vec2d);
* while (i.hasNext()) cout << i.next();
*/
类似题目:
[LeetCode] 341. Flatten Nested List Iterator 压平嵌套链表迭代器
All LeetCode Questions List 题目汇总
[LeetCode] 251. Flatten 2D Vector 压平二维向量的更多相关文章
- [LeetCode] Flatten 2D Vector 压平二维向量
Implement an iterator to flatten a 2d vector. For example,Given 2d vector = [ [1,2], [3], [4,5,6] ] ...
- LeetCode 251. Flatten 2D Vector
原题链接在这里:https://leetcode.com/problems/flatten-2d-vector/ 题目: Implement an iterator to flatten a 2d v ...
- 用vector实现二维向量
如果一个向量的每一个元素是一个向量,则称为二维向量,例如 vector<vector<int> >vv(3, vector<int>(4));//这里,两个“> ...
- 251. Flatten 2D Vector 平铺二维矩阵
[抄题]: Implement an iterator to flatten a 2d vector. Example: Input: 2d vector = [ [1,2], [3], [4,5,6 ...
- 251. Flatten 2D Vector
题目: Implement an iterator to flatten a 2d vector. For example,Given 2d vector = [ [1,2], [3], [4,5,6 ...
- [Leetcode] search a 2d matrix 搜索二维矩阵
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...
- [Swift]LeetCode251.展平二维向量 $ Flatten 2D Vector
Implement an iterator to flatten a 2d vector. For example,Given 2d vector = [ [1,2], [3], [4,5,6] ] ...
- Leetcode之二分法专题-240. 搜索二维矩阵 II(Search a 2D Matrix II)
Leetcode之二分法专题-240. 搜索二维矩阵 II(Search a 2D Matrix II) 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target.该矩阵 ...
- [VB.NET][C#]二维向量的基本运算
前言 在数学中,几何向量指具有大小(Magnitude)和方向的几何对象,它在线性代数中经由抽象化有着更一般的概念.向量在编程中也有着及其广泛的应用,其作用在图形编程和游戏物理引擎方面尤为突出. 基于 ...
随机推荐
- 如何查看已购买的office密钥
登陆这个网址https://account.microsoft.com/services/ 声明 :转载请注明来源sogeisetsu.cnblogs.com
- app开发-2
一.app登录注册实现 1.首先进行布局,mhead,mbody 在app index.html内创建一个 a链接通过mui.openWindow跳到登录页面 <a class="mu ...
- luoguU60884 【模板】动态点分治套线段树
题目连接:https://www.luogu.org/problemnew/show/U60884 题意:有N个点,标号为1∼N,用N−1条双向带权通道连接,保证任意两个点能互相到达. Q次询问,问从 ...
- centos7部署inotify与rsync实现实时数据同步
实验环境:CentOS Linux release 7.6.1810 node1:192.168.216.130 客户端(向服务端发起数据同步) node2:192.168.216.132 服务端(接 ...
- 3.Vue 实例
创建一个 Vue 实例 每个 Vue 应用都是通过用 Vue 函数创建一个新的 Vue 实例开始的: var vm = new Vue({ // 选项 }) 虽然没有完全遵循 MVVM 模型,但是 V ...
- 洛谷 UVA12563 Jin Ge Jin Qu hao 题解
这道题其实是一道01背包的变形题,主要思路如下:在不把剩余时间用光的前提下(剩余时间>0),尽可能的多唱歌.于是我们可以用dp[i]表示的是到当前i秒时,最多可以唱多少歌. 状态转换方程:dp[ ...
- /proc/pid/statm content analysis
root@am335x-ec:/# cat /proc/1/statm 6141 1181 699 232 0 4641 0 Table 1-3: Contents of the statm file ...
- 关于System.Reflection.TargetInvocationException 异常
什么是TargetInvocationException 由通过反射调用的方法引发的异常. 继承 Object Exception ApplicationException TargetInvocat ...
- vigil rpm 包制作
vigil 可以方便的进行服务的监控,以下尝试制作一个rpm 包,方便使用 安装依赖 ruby yum -y install ruby rubygems ruby-devel 修改gem 源 可选, ...
- pgloader 学习(一)支持的特性
pgloader 是一个不错的多种格式数据同步到pg 的工具,pgloader 使用postrgresql 的copy 协议进行高效的数据同步处理 特性 加载文件到内容pg 多种数据源格式的支持 cs ...