Skip to content

Latest commit

 

History

History
71 lines (52 loc) · 1.3 KB

0251._Flatten_2D_Vector.md

File metadata and controls

71 lines (52 loc) · 1.3 KB

251. Flatten 2D Vector

难度: Medium

刷题内容

原题连接

内容描述

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 false, 
             the order of elements returned by next should be: [1,2,3,4,5,6].

解题方案

思路 1

class Vector2D(object):

    def __init__(self, vec2d):
        """
        Initialize your data structure here.
        :type vec2d: List[List[int]]
        """
        self.row = 0
        self.col = 0
        self.vec = vec2d
        

    def next(self):
        """
        :rtype: int
        """
        res = self.vec[self.row][self.col]
        self.col += 1
        return res
        

    def hasNext(self):
        """
        :rtype: bool
        """
        while self.row < len(self.vec):
            if self.col < len(self.vec[self.row]):
                return True
            self.col = 0
            self.row += 1
        return False
        

# Your Vector2D object will be instantiated and called as such:
# i, v = Vector2D(vec2d), []
# while i.hasNext(): v.append(i.next())