LeetCode - 251展开二维向量(设计 迭代器 双指针)*

LeetCode - 251展开二维向量(设计 迭代器 双指针)*_第1张图片
LeetCode - 251展开二维向量(设计 迭代器 双指针)*_第2张图片
LeetCode - 251展开二维向量(设计 迭代器 双指针)*_第3张图片

class Vector2D {
    List<Integer> list = new ArrayList<>();//将二维向量存放到一维数组中
    int pos = 0;
    public Vector2D(int[][] vec) {
        for(int[] v: vec){
            for(int n : v){
                list.add(n);
            }
        }
    }
    
    public int next() {
       int res = list.get(pos);
       pos++;//指针向后移
       return res;
    }
    
    public boolean hasNext() {
        return pos < list.size();
    }
}

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D obj = new Vector2D(vec);
 * int param_1 = obj.next();
 * boolean param_2 = obj.hasNext();
 */

双指针

LeetCode - 251展开二维向量(设计 迭代器 双指针)*_第4张图片
LeetCode - 251展开二维向量(设计 迭代器 双指针)*_第5张图片

import java.util.NoSuchElementException;
class Vector2D {
    private int[][] vector;
    private int outer = 0;
    private int inner = 0;
    public Vector2D(int[][] vec) {
         vector = vec;
    }
    public void advanceNext(){
        while(outer < vector.length && inner == vector[outer].length){
            outer += 1;
            inner = 0;
        }
    }
    public int next() {
        if(!hasNext())
            throw new NoSuchElementException();
        return vector[outer][inner++];
    }
    
    public boolean hasNext() {
        advanceNext();
        return outer < vector.length;
    }
}

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D obj = new Vector2D(vec);
 * int param_1 = obj.next();
 * boolean param_2 = obj.hasNext();
 */

你可能感兴趣的:(leetcode,设计,leetcode,算法,java)