Saturday, February 8, 2020

Leetcode 251 @ Flattern 2D Vector

Design and implement an iterator to flatten a 2d vector. It should support the following operations: next and hasNext.

Example:
Vector2D iterator = new Vector2D([[1,2],[3],[4]]);

iterator.next(); // return 1
iterator.next(); // return 2
iterator.next(); // return 3
iterator.hasNext(); // return true
iterator.hasNext(); // return true
iterator.next(); // return 4
iterator.hasNext(); // return false

Notes:
  1. Please remember to RESET your class variables declared in Vector2D, as static/class variables are persisted across multiple test cases. Please see here for more details.
  2. You may assume that next() call will always be valid, that is, there will be at least a next element in the 2d vector when next() is called.
这道题很简单,没什么复杂。唯一要注意的一点是,2D vector的每一行的大小不一定一样,所以用 v.size() * v[0].size() 去计算总体的大小是不对的。以及v传进来后,要把它放入自己的数据结构,就是把它flattern,一维化。


class Vector2D {
    int index;
    vector<int> data;
public:
    Vector2D(vector<vector<int>>& v) {
        for (auto &row : v)
        {
            for (int &it : row)
            {
                data.push_back(it);
            }
        }
        index = 0;
    }
    
    int next() {
        return data[index++];
    }
    
    bool hasNext() {
         return index < data.size();
    }
};

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

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...