simple java beat 98.64%


  • 0
    T
    public class NestedIterator implements Iterator<Integer> {
    
        private List<Integer> integers;
        private int i = 0;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            this.integers = new ArrayList<>();
            for (NestedInteger integer: nestedList)
                getAll(integer, integers);
        }
    
        private void getAll(NestedInteger nestedInteger, List<Integer> res){
            if (nestedInteger != null){
                if (nestedInteger.isInteger()){
                    res.add(nestedInteger.getInteger());
                }
                else {
                    for (NestedInteger integer: nestedInteger.getList()){
                        getAll(integer, res);
                    }
                }
            }
        }
    
        @Override
        public Integer next() {
            return integers.get(i++);
        }
    
        @Override
        public boolean hasNext() {
            return i != integers.size();
        }
    }
    

Log in to reply
 

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