Java two line solution


  • 0
    Y
     public class ZigzagIterator {
        private int common = 0;
        private List<Integer> list1 = new ArrayList<>();
        private List<Integer> list2 = new ArrayList<>();
        private int pointer = 0;
    
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            this.list1 = v1;
            this.list2 = v2;
            this.common = Math.min(v1.size(), v2.size()) * 2;
        }
    
        public int next() {
            return (pointer < common) 
                ? (pointer % 2 == 0 ? list1.get(pointer++ / 2) : list2.get(pointer++ / 2)) 
                : (list1.size() > list2.size() ? list1.get(pointer++ - common/2) : list2.get(pointer++ - common/2));
        }
    
        public boolean hasNext() {
            return pointer < list1.size() + list2.size();
        }
    }
    

Log in to reply
 

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