251. Flatten 2D Vector

Posted 咖啡中不塌缩的方糖

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:

  1. How many variables do you need to keep track?
  2. Two variables is all you need. Try with x and y.
  3. Beware of empty rows. It could be the first few rows.
  4. To write correct code, think about the invariant to maintain. What is it?
  5. The invariant is x and y must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it?
  6. Not sure? Think about how you would implement hasNext(). Which is more complex?
  7. Common logic in two different places should be refactored into a common method.

 

 

 

public class Vector2D {
    public IList<IList<int>> v {get;set;}
    private int verticalCount {get;set;}
    private int index {get;set;}
    public Vector2D(IList<IList<int>> vec2d) {
        v= vec2d;
        verticalCount = 0;
        index = 0;
    }

    public bool HasNext() {
        if(verticalCount >= v.Count()) return false;
        if(verticalCount == v.Count()-1 && index >= v[verticalCount].Count()) return false;
        if(index >=  v[verticalCount].Count())
        {
            verticalCount++;
            while(verticalCount < v.Count() &&  v[verticalCount].Count() == 0)
            {
                verticalCount++;
            }
            if(verticalCount ==  v.Count()) return false;
            else 
            {
                index = 0;
                return true;
            }
           
        }
        return true;
    }

    public int Next() {
        return v[verticalCount][index++];
    }
}

/**
 * Your Vector2D will be called like this:
 * Vector2D i = new Vector2D(vec2d);
 * while (i.HasNext()) v[f()] = i.Next();
 */

 

以上是关于251. Flatten 2D Vector的主要内容,如果未能解决你的问题,请参考以下文章

251. Flatten 2D Vector

251. Flatten 2D Vector 平铺二维矩阵

keras 中的 Flatten() 和 GlobalAveragePooling2D() 有啥区别

java 251.展平2D矢量(#)。java

java 251.展平2D矢量(#)。java

java 251.展平2D矢量(#)。java