Java O(1) for two operations, and never change the input list


  • 0
    S
    public class ZigzagIterator {
        
        int len1, len2, len, index;
        List<Integer> v1, v2;
    
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            this.index = 0;
            this.v1 = v1;
            this.v2 = v2;
            len1 = v1.size();
            len2 = v2.size();
            len = len1 + len2;
        }
    
        public int next() {
            int res = 0;
            if(len1 < len2 && index >= 2*len1) {
                res = v2.get(index-len1);
            } else if(len1 > len2 && index >= 2*len2) {
                res = v1.get(index-len2);
            } else {
                if(index%2 == 0) res = v1.get(index/2);
                else res = v2.get(index/2);
            }
            index++;
            return res;
        }
    
        public boolean hasNext() {
            if(index == len) return false;
            return true;
        }
    }

Log in to reply
 

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