easy, just take turns to go each list


  • 0
    H
        List<Integer> v1;
        List<Integer> v2;
        int i = 0;
        int j = 0;
        boolean first = true;
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            this.v1 = v1;
            this.v2 = v2;
        }
    
        public int next() {
            while (hasNext()) {
                if (first) {
                	first = false;
                    if (i < v1.size())
                    	return v1.get(i++);
                }
        
                if (!first) {
                	first = true;
                	if (j < v2.size())
                		return v2.get(j++);
                }
        	}
        	throw new RuntimeException("no more data");
        }
    
        public boolean hasNext() {
            return i < v1.size() || j < v2.size();
        }
    

Log in to reply
 

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