Created
December 27, 2023 20:58
-
-
Save primaryobjects/ff33faac5bd5f0c8d207bc767fbb0e4f to your computer and use it in GitHub Desktop.
Design Dynamic Array (Resizable Array) https://neetcode.io/problems/dynamicArray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DynamicArray { | |
/** | |
* @constructor | |
* @param {number} capacity | |
*/ | |
constructor(capacity) { | |
this.data = new Array(capacity); | |
this.num_elements = 0; | |
} | |
/** | |
* @param {number} i | |
* @returns {number} | |
*/ | |
get(i) { | |
return this.data[i]; | |
} | |
/** | |
* @param {number} i | |
* @param {number} n | |
* @returns {void} | |
*/ | |
set(i, n) { | |
this.data[i] = n; | |
} | |
/** | |
* @param {number} n | |
* @returns {void} | |
*/ | |
pushback(n) { | |
if (this.num_elements === this.data.length) { | |
this.resize(); | |
} | |
this.set(this.num_elements++, n); | |
} | |
/** | |
* @returns {number} | |
*/ | |
popback() { | |
const val = this.get(this.num_elements - 1); | |
this.set(this.num_elements - 1, undefined); | |
this.num_elements--; | |
return val; | |
} | |
/** | |
* @returns {void} | |
*/ | |
resize() { | |
const newArr = new Array(this.data.length * 2); | |
for (let i=0; i<this.data.length; i++) { | |
newArr[i] = this.get(i); | |
} | |
this.data = newArr; | |
} | |
/** | |
* @returns {number} | |
*/ | |
getSize() { | |
return this.num_elements; | |
} | |
/** | |
* @returns {number} | |
*/ | |
getCapacity() { | |
return this.data.length; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment