Java Iterator 4ms


  • 0
    D
        class Vector2D {
    
    	    private Iterator outerIterator;
    	    private Iterator innerIterator;
    
    	    public Vector2D(List<List<Integer>> vec2d) {
    		    outerIterator = vec2d.iterator();
    	    }
    
    	    public int next() {
    		    return (int) innerIterator.next();
    	    }
    
    	    public boolean hasNext() {
    		    if (innerIterator != null && innerIterator.hasNext()) {
    			    return true;
    		    } else {
    			    while (outerIterator.hasNext()) {
    				    List sublist = (List) outerIterator.next();
    				    innerIterator = sublist.iterator();
    				    if (innerIterator.hasNext()) {
    					    return true;
    				    }
    			    }
    		    }
    		    return false;
    	    } 
        }

  • 0
    F

    The same by using Iterator

    public class Vector2D {
    
    Iterator<List<Integer>> iter2d;
    Iterator<Integer> iter1d;
    
    public Vector2D(List<List<Integer>> vec2d) {
        iter2d = vec2d.size()>0 ? vec2d.listIterator() : null;
        iter1d = null;
    }
    
    public int next() {
        return iter1d.next();
    }
    
    public boolean hasNext() {
        if(iter2d==null) return false;
        if(iter1d!=null && iter1d.hasNext()) return true;
        if(iter2d.hasNext()) {
            List<Integer> list = iter2d.next();
            while(list.size()==0 && iter2d.hasNext()) list = iter2d.next();
            if(list.size()==0) return false;
            else {
                iter1d = list.listIterator();
                return true;
            }
        }
        else return false;
    }
    }

Log in to reply
 

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