My Very simple solution in Java


  • -1
    T
    public class ZigzagIterator {
        int first = -1;
        int second = -1;
        int firstEnd = -1;
        int secondEnd = -1;
        List<Integer> l1 = null;
        List<Integer> l2 = null;
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            if(v1.size()>0){
                first= 0;
                firstEnd = v1.size();
                l1 = v1;
            }
            if(v2.size()>0){
                second = 0;
                l2 = v2;
                secondEnd = v2.size();
            }
        }
    
        public int next() {
            if(first!=-1 && second!=-1){
                if(first == second){
                    if(first < firstEnd){
                        int temp = l1.get(first);
                        first++;
                        return temp;
                    }else{
                        //if first is out of bounds
                        if(second<secondEnd){
                            int temp = l2.get(second++);
                            return temp;
                        }else return -1;
                    }
                }else{
                    //time for second
                    if(second<secondEnd){
                        return l2.get(second++);
                    }else{
                        if(first<firstEnd){
                            int temp = l1.get(first++);
                            return temp;
                        }else return -1;
                    }
                }
            }else{
                if(first == -1){
                    if(second<secondEnd) return l2.get(second++);
                    else return -1;
                }else if(second == -1){
                    if(first<firstEnd) return l1.get(first++);
                    else return -1;
                }else return -1;
            }
        }
    
        public boolean hasNext() {
            return (first<firstEnd || second < secondEnd);
        }
    }
    
    /**
     * Your ZigzagIterator object will be instantiated and called as such:
     * ZigzagIterator i = new ZigzagIterator(v1, v2);
     * while (i.hasNext()) v[f()] = i.next();
     */
    
    

Log in to reply
 

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