Leetcode P0251"Flatten 2D Vector" 题解

2021/04/10 Leetcode

博文中会简要介绍Leetcode P0251题目分析及解题思路。

“Flatten 2D Vector”是一道比较简单的题目。题目要求对给定的所有向量执行展开操作,将所有向量元素“铺平“,并可以使用类似于迭代器的方式遍历。

Design an iterator to flatten a 2D vector. It should support the next and hasNext operations.

Implement the Vector2D class:

  • Vector2D(int[][] vec) initializes the object with the 2D vector vec.
  • next() returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to next are valid.
  • hasNext() returns true if there are still some elements in the vector, and false otherwise.

以下是Java的题解代码实现。

class Vector2D {
    private int ptr = 0, end = 0;
    private List<Integer> elements = new ArrayList<>();
    
    public Vector2D(int[][] vec) {
        for (int[] v: vec) {
            for (int e: v) {
                elements.add(e);
                this.end += 1;
            }
        }
    }
    
    public int next() {
        return elements.get(ptr++);
    }
    
    public boolean hasNext() {
        return (ptr < end);
    }
}

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D obj = new Vector2D(vec);
 * int param_1 = obj.next();
 * boolean param_2 = obj.hasNext();
 */

以下是C++的题解代码实现。

class Vector2D {
public:
    Vector2D(vector<vector<int>>& vec) {
        for (vector<int> v: vec) {
            for (int e: v) {
                _elems.push_back(e);
                _end++;
            }
        }
    }
    
    int next() {
        return _elems[_p++];
    }
    
    bool hasNext() {
        return (_p < _end);
    }
    
private:
    vector<int> _elems;
    int _p = 0, _end = 0;
};

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D* obj = new Vector2D(vec);
 * int param_1 = obj->next();
 * bool param_2 = obj->hasNext();
 */

Search

    Table of Contents