其实本题没有我想的那么难,就是到很普通的基础题,只需要注意在每次hasNext()的时候,set()一下就成了(也许col outOfIndex)

    时间复杂度:

    • Constructor: 251. Flatten 2D Vector - 图1
    • set():
      • 251. Flatten 2D Vector - 图2: inner array的数量
      • 251. Flatten 2D Vector - 图3:总共的number
      • 一共调用251. Flatten 2D Vector - 图4次,真正运行过251. Flatten 2D Vector - 图5次,所以平均时间复杂度是251. Flatten 2D Vector - 图6
    • next()/hasNext(): 既可能是,也可能是

    代码如下:

    1. class Vector2D {
    2. private int row;
    3. private int col;
    4. private int[][] arr;
    5. public Vector2D(int[][] v) {
    6. this.arr = v;
    7. this.row = 0;
    8. this.col = 0;
    9. }
    10. private void set() {
    11. while (row < arr.length && col == arr[row].length) {
    12. col = 0;
    13. ++row;
    14. }
    15. }
    16. public int next() {
    17. if (!hasNext()) {
    18. throw new java.util.NoSuchElementException();
    19. }
    20. return arr[row][col++];
    21. }
    22. public boolean hasNext() {
    23. set();
    24. return row < arr.length;
    25. }
    26. }
    27. /**
    28. * Your Vector2D object will be instantiated and called as such:
    29. * Vector2D obj = new Vector2D(v);
    30. * int param_1 = obj.next();
    31. * boolean param_2 = obj.hasNext();
    32. */