LintCode 540. Zigzag Iterator 原创Java参考解答

LintCode 540. Zigzag Iterator 原创Java参考解答

问题描述

http://www.lintcode.com/en/problem/zigzag-iterator/

Given two 1d vectors, implement an iterator to return their elements alternately.

Example

Given two 1d vectors:

v1 = [1, 2]
v2 = [3, 4, 5, 6]

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]

解题思路

题目是设计一个穿梭遍历两个数组的iterator。

  • 关键点:三个变量。分别遍历list1,list2的iterator变量以及决定下一个数是从v1还是从v2里拿的turns变量。

参考代码

public class ZigzagIterator { 
    /** 
     * @param v1 v2 two 1d vectors 
     */ 
    public Iterator<Integer> it1; 
    public Iterator<Integer> it2; 
    public int turns; 
     
    public ZigzagIterator(List<Integer> v1, List<Integer> v2) { 
        // initialize your data structure here. 
        this.it1 = v1.iterator(); 
        this.it2 = v2.iterator(); 
        turns = 0; 
    } 
 
    public int next() { 
        turns++; 
        if ((turns % 2 == 1 && it1.hasNext()) || (!it2.hasNext())) { 
            return it1.next(); 
        } else if ((turns % 2 == 0 && it2.hasNext()) || (!it1.hasNext())) { 
            return it2.next(); 
        } else { 
            return -1; 
        } 
    } 
 
    public boolean hasNext() { 
        return it1.hasNext() || it2.hasNext();         
    } 
} 
 
/** 
 * Your ZigzagIterator object will be instantiated and called as such: 
 * ZigzagIterator solution = new ZigzagIterator(v1, v2); 
 * while (solution.hasNext()) result.add(solution.next()); 
 * Output result 
 */ 

相关题目

LintCode All in One 原创题目讲解汇总

LintCode 541. Zigzag Iterator II 原创Java参考解答

发表回复

您的电子邮箱地址不会被公开。