标签:
Given two 1d vectors, implement an iterator to return their elements alternately. For 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]. Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases? Clarification for the follow up question - Update (2015-09-18): The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For example, given the following input: [1,2,3] [4,5,6,7] [8,9] It should return [1,4,8,2,5,9,3,6,7].
1 public class ZigzagIterator { 2 List<Integer> l1; 3 List<Integer> l2; 4 int cnt1; 5 int cnt2; 6 7 public ZigzagIterator(List<Integer> v1, List<Integer> v2) { 8 this.l1 = v1; 9 this.l2 = v2; 10 this.cnt1 = 0; 11 this.cnt2 = 0; 12 } 13 14 public int next() { 15 if (cnt1<l1.size() && cnt2<l2.size()) { 16 if (cnt1 == cnt2) { 17 cnt1++; 18 return l1.get(cnt1-1); 19 } 20 else { 21 cnt2++; 22 return l2.get(cnt2-1); 23 } 24 } 25 else if (cnt1 < l1.size()) { 26 cnt1++; 27 return l1.get(cnt1-1); 28 } 29 else if (cnt2 < l2.size()) { 30 cnt2++; 31 return l2.get(cnt2-1); 32 } 33 else return Integer.MIN_VALUE; 34 } 35 36 public boolean hasNext() { 37 return (cnt1<l1.size()) || (cnt2<l2.size()); 38 } 39 } 40 41 /** 42 * Your ZigzagIterator object will be instantiated and called as such: 43 * ZigzagIterator i = new ZigzagIterator(v1, v2); 44 * while (i.hasNext()) v[f()] = i.next(); 45 */
标签:
原文地址:http://www.cnblogs.com/EdwardLiu/p/5077512.html