zoukankan      html  css  js  c++  java
  • 251. Flatten 2D Vector

    package LeetCode_251
    
    /**
     * 251. Flatten 2D Vector
     * (Prime)
     * Design and implement an iterator to flatten a 2d vector. It should support the following operations: next and hasNext.
    
    Example:
    Vector2D iterator = new Vector2D([[1,2],[3],[4]]);
    iterator.next(); // return 1
    iterator.next(); // return 2
    iterator.next(); // return 3
    iterator.hasNext(); // return true
    iterator.hasNext(); // return true
    iterator.next(); // return 4
    iterator.hasNext(); // return false
    
    Notes:
    1. Please remember to RESET your class variables declared in Vector2D,
    as static/class variables are persisted across multiple test cases. Please see here for more details.
    2. You may assume that next() call will always be valid, that is,
    there will be at least a next element in the 2d vector when next() is called.
     * */
    
    /*
    * Solution: change 2d array into 1d array
    * */
    class Vector2D(twoDArray: Array<IntArray>) {
    
        var array: IntArray? = null
        var index = 0
        var size = 0
    
        init {
            //calculate the size of 1d array
            for (array in twoDArray) {
                size += array.size
            }
            array = IntArray(size)
            //fill array
            var i = 0
            for (array_ in twoDArray) {
                for (num in array_) {
                    array!![i++] = num
                }
            }
        }
    
        fun next(): Int {
            return array!![index++]
        }
    
        fun hasNext(): Boolean {
            return index < size
        }
    }
  • 相关阅读:
    获取经纬度 CLLocation
    获取手机 IP
    UIBeaierPath 与 CAShapeLayer
    导航栏转场动画CATransition
    UITextField输入限制/小数/首位等
    程序进入后台继续执行
    发送短信
    网络AFNetworking 3.1
    UIBezierPath
    CoreAnimation 核心动画 / CABasicAnimation/ CAKeyframeAnimation
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13569030.html
Copyright © 2011-2022 走看看