Monday, May 20, 2019

Lintcode 22. Flatten List

Given a list, each element in the list can be a list or integer. flatten it into a simply list with integers.

Example

Example 1:
 Input:  [[1,1],2,[1,1]]
 Output: [1,1,2,1,1]
 
 Explanation:
 flatten it into a simply list with integers.

Example 2:
 Input:  [1,2,[1,2]]
 Output:[1,2,1,2]
 
 Explanation:  
 flatten it into a simply list with integers.

Example 3:
 Input: [4,[3,[2,[1]]]]
 Output:[4,3,2,1]
 
 Explanation: 
 flatten it into a simply list with integers.

Challenge

Do it in non-recursive.

Notice

If the element in the given list is a list, it can contain list too.
Code (Java):
/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *
 *     // @return true if this NestedInteger holds a single integer,
 *     // rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds,
 *     // if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // @return the nested list that this NestedInteger holds,
 *     // if it holds a nested list
 *     // Return null if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
import java.util.Iterator;

public class Solution {

    // @param nestedList a list of NestedInteger
    // @return a list of integer
    public List<Integer> flatten(List<NestedInteger> nestedList) {
        // Write your code here
        NestedIntegerIterator it = new NestedIntegerIterator(nestedList);
        
        List<Integer> ans = new ArrayList<>();
        while (it.hasNext()) {
            ans.add(it.next());
        }
        
        return ans;
    }
}

class NestedIntegerIterator implements Iterator<Integer> {
    private Stack<NestedInteger> stack;
    
    public NestedIntegerIterator(List<NestedInteger> nestedList) {
        stack = new Stack<>();
        fillStack(nestedList);
    }
    
    @Override
    public Integer next() {
        Integer ans = null;
        if (hasNext()) {
            ans = stack.pop().getInteger();
        }
        return ans;
    } 
    
    @Override
    public boolean hasNext() {
        while (!stack.isEmpty() && !stack.peek().isInteger()) {
            NestedInteger nestInteger = stack.pop();
            fillStack(nestInteger.getList());
        }
        
        return !stack.isEmpty();
    }
    
    @Override
    public void remove() {
        
    }
    
    private void fillStack(List<NestedInteger> list) {
        for (int i = list.size() - 1; i >= 0; i--) {
            stack.push(list.get(i));
        }
    }
}

No comments:

Post a Comment