Simple intuitive java solution, can apply to k vectors


  • 0
    C

    no fancy things, very intuitive solution

    public class ZigzagIterator {
        ArrayList<Integer> list;
        int n=0;
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            list = new ArrayList<Integer>();
            int pos = 0;
            boolean end = false;
            while(!end){
                end = true;
               //for k vectors, use a for loop here
                if(v1.size() > pos){
                    list.add(v1.get(pos));
                    end = false;
                }
                if(v2.size() > pos){
                    list.add(v2.get(pos));
                    end = false;
                }
                pos++;
            }
        }
        public int next() {
            return list.get(n++);
        }
    
        public boolean hasNext() {
            return n < list.size();
        }
    }
    

Log in to reply
 

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