[HackerRank] Dynamic Array
/** * https://www.hackerrank.com/challenges/dynamic-array/problem * */ class DynamicArray { var lastAnswer = 0 var answerList: ArrayList<Int>? = null var seqs: ArrayList<ArrayList<Int>>? = null fun dynamicArray(n: Int, queries: Array<Array<Int>>): Array<Int> { seqs = ArrayList<ArrayList<Int>>() for (i in 0 until n) { seqs!!.add(ArrayList<Int>()) } answerList = ArrayList() val size = queries.size for (i in 0 until size) { val type = queries[i][0] val x = queries[i][1] val y = queries[i][2] val seqIndex = (x xor lastAnswer) % n when (type) { 1 -> { val list = seqs!!.get(seqIndex) list.add(y) } 2 -> { val list = seqs!![seqIndex] val index = y % list.size lastAnswer = list.get(index) answerList!!.add(lastAnswer) } } } val count = answerList!!.size val array = Array<Int>(count, { 0 }) answerList!!.toArray(array) return array } }