Very Clean Java Solution Using Iterators


  • 1

    This question is very good! Even though I can solve much harder algorithmic problems, I have so hard time solving this problem!!!!!!!

    It is very easy to lose the invariants unless carefully thinking about it and any boundary cases.

    Below is my answer, which may look the code better.

    public class Vector2D {
    
        Iterator<List<Integer>> lItr;
        Iterator<Integer> iItr;
    
        public Vector2D(List<List<Integer>> vec2d) {
            lItr = vec2d.iterator();
            iItr = lItr.hasNext() ? lItr.next().iterator() : null;
        }
    
        public int next() {
            hasNext();
            return iItr.next();
        }
    
        public boolean hasNext() {
            if(iItr==null)
                return false;
            else if(iItr.hasNext())
                return true;
            else {
                while(lItr.hasNext()) {
                    iItr = lItr.next().iterator();
                    if(iItr.hasNext())
                        return true;
                }
                return false;
            }
        }
    }

  • 0
    M

    upvoted... but this is not that hard at all, lol...

    below is my implementation, which is a little different from yours.

    https://leetcode.com/discuss/82590/share-simple-using-built-iterators-demanded-follow-beats-times


Log in to reply
 

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