Leetcode - 251. Flatten 2D Vector

숲사람·2023년 8월 12일
0

멘타트 훈련

목록 보기
223/237

문제

2D 벡터를 flat하게 만드는 iterator를 디자인해라.

Input
["Vector2D", "next", "next", "next", "hasNext", "hasNext", "next", "hasNext"]
[[[[1, 2], [3], [4]]], [], [], [], [], [], [], []]
Output
[null, 1, 2, 3, true, true, 4, false]

Explanation
Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]);
vector2D.next();    // return 1
vector2D.next();    // return 2
vector2D.next();    // return 3
vector2D.hasNext(); // return True
vector2D.hasNext(); // return True
vector2D.next();    // return 4
vector2D.hasNext(); // return False

아이디어

  • 풀이1
    2차원 벡터를 1차원 벡터에 복사 O(n)

풀이 1

class Vector2D {
public:
    vector<int> flat;
    int cur = 0;
    Vector2D(vector<vector<int>>& vec) {
        for (int i = 0; i < vec.size(); i++)
            for (int j = 0; j < vec[i].size(); j++)
                flat.push_back(vec[i][j]);
    }
    
    int next() {
        return flat[cur++];
    }
    
    bool hasNext() {
        return cur < flat.size();
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

1개의 댓글

comment-user-thumbnail
2023년 8월 12일

많은 도움이 되었습니다, 감사합니다.

답글 달기