Java - Very simple & easy to understand O(1) space solution


  • 0
    T
    public class Vector2D implements Iterator<Integer> {
        List<List<Integer>> result;
        List<Integer> temp;
        int i;
        int j;
        
        public Vector2D(List<List<Integer>> vec2d) {
           result = vec2d;
           i=0;
           if(result == null || result.size()==0) temp = new ArrayList<>();
           else temp = result.get(i);
           j=0;
        }
    
    @Override
        public Integer next() {
            if(j<temp.size()){
                int res = temp.get(j);
                j++;
                return res;
            }else{
                j=0;
                temp = result.get(i);
                int res = temp.get(j);
                j++;
                return res;
            }
        }
    
    @Override
        public boolean hasNext() {
            if(j<temp.size()){
                return true;
            }else{
                do{
                    i++;
                }while(i<result.size() && result.get(i).size()==0);
                return i<result.size();
            }
        }
    }
    

    /**

    • Your Vector2D object will be instantiated and called as such:
    • Vector2D i = new Vector2D(vec2d);
    • while (i.hasNext()) v[f()] = i.next();
      */>! Spoiler

Log in to reply
 

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