Java solution with O(n) time


  • 0
    R

    public class Vector2D implements Iterator<Integer> {

    int size;
    int index;
    List<List<Integer>> veccon;
    public Vector2D(List<List<Integer>> vec2d) {
        if (vec2d == null || vec2d.size() == 0) return;
        veccon = new ArrayList<List<Integer>>();
        size = 0;
        index = 0;
        for (int i = 0; i < vec2d.size(); i++) {
            List<Integer> temp = vec2d.get(i);
            if (temp == null || temp.size() == 0) continue;
            veccon.add(new ArrayList<Integer>(temp));
            size += temp.size();
            //for (int j = 0; j < temp.size(); j++) {
                //veccon.add(new ArrayList<Integer>(temp));
                //size += temp.size();
            //}
        }
    }
    
    @Override
    public Integer next() {
        while (veccon.get(index).size() == 0) {
            index++;
        }
        size--;
        return veccon.get(index).remove(0);
    }
    
    @Override
    public boolean hasNext() {
        return size > 0;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.