Design 类

2019-02-18  本文已影响0人  YOLO哈哈哈
1.Zigzag Iterator(281. leetcode)

-1.这里会复习到 java 的iterator 概念
iterator : 每个list 都有一个自己的iterator object

public class ZigzagIterator {
    LinkedList<Iterator> list;
    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
         list = new LinkedList<>();
         if( ! v1.isEmpty()) list.add( v1.iterator() );
          if( !v2.isEmpty()) list.add( v2.iterator() );
    }

    public int next() {
     Iterator poll = list.remove();
     int res = (Integer) poll.next();
     if( poll.hasNext() ) list.add(iterator);
    return res; 
    }

    public boolean hasNext() {
        return !list.isEmpty();
    }
}

方法二: 不使用iterator ,用index 实现 iterator
**注意点: ** 从构造函数中 传进来的 parameter , 其他function 是不能拿到的, 所以需要在 class 的data 区域 declare 一个指针, 指向这个parameter

public class ZigzagIterator {
    List<Integer> v1;
    List<Integer> v2;
    int index1;
    int index2;
    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        this.v1 = v1;
        this.v2 = v2;
        index1 = 0;
        index2 =0;
    }
    public int next() {
        if( index1 == v1.size() ){
            index2++;
            return v2.get(index2 -1);
        }
      if( index2 == v2.size()) {
          index1 ++;
          return v1.get( index1 -1);
      }
    if( index1 < = index2) {
      index1 ++;
      return v1.get(index1 - 1);
    }else{
      index2++;
      return v2.get( index2 -1 );
    }
  }

    public boolean hasNext() {
        return index1 < v1.size() || index2 < v2.size() ; 
    }
   
}
2.Peeking Iterator(284. leetcode)
/ Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
    
    private Iterator<Integer> iter;
    private boolean curr;
    private int nextInt;
    
    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        iter = iterator;
        curr = false;
    }

    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        if(curr != true){
            nextInt = iter.next();
            curr = true;
        }
        return nextInt;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        if(curr){
            curr = false;
            return nextInt;
        } 
        else{
            return iter.next();
        }
    }

    @Override
    public boolean hasNext() {
        return curr || iter.hasNext();
    }
}
上一篇下一篇

猜你喜欢

热点阅读