Java Solution for K inputs with explaination


  • 0
    C
    public class ZigzagIterator {
        private List<List<Integer>> listBank = new ArrayList<List<Integer>>();
        
        // where each entry[0] represents listBank index and entry[1] represents index of a list in listBank
        private List<int[]> index = new ArrayList<int[]>();
        
        private int currentIdx = 0;
        // as per the followup question, if there are k list we need to put it in a for loop and ignore the empty list.
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            int count = 0;
            if(!v1.isEmpty()){
                listBank.add(v1);
                index.add(new int[]{count++, 0});
            }
            if(!v2.isEmpty()){
                listBank.add(v2);
                index.add(new int[]{count++, 0});
            }
        }
    
        public int next() {
            int[] nextIdx = index.get(currentIdx);
            int val = listBank.get(nextIdx[0]).get(nextIdx[1]);
            nextIdx[1]++;
            
            // if the current list is completely consumed its time to remove it from the collection
            if(nextIdx[1] == listBank.get(nextIdx[0]).size()){
                index.remove(currentIdx);
            }
            else{
                currentIdx++;
            }
            
            // this is required to prevent modulus execution when index size becomes 0
            if(!index.isEmpty()){
                // reseting the pointer of current so that it behave as a circular list
                currentIdx %= index.size();
            }
            else{
                currentIdx=0;
            }
            
            return val;
        }
    
        public boolean hasNext() {
            return !index.isEmpty();
        }
    }
    

Log in to reply
 

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