Udemy: Master Coding Interview - Arrays - #66

Run Settings
LanguageC#
Language Version
Run Command
using System; class Array { public int length = 0; private int size = 1; private Object[] data; static void Main() { Array newArray = new Array(); newArray.push("hi"); newArray.push("you"); newArray.push("!"); //newArray.pop(); newArray.delete(0); newArray.push("are"); newArray.push("nice"); newArray.delete(1); Console.WriteLine("Array contents: " + newArray.toString()); } public Array() { this.data = new Object[size]; } public Object get(int index) { return this.data[index]; } public void push(Object item) { resizeArrayIfNeeded(); data[length] = item; length++; } public Object pop() { Object item = this.data[this.length - 1]; this.length--; resizeArrayIfNeeded(); return item; } public string toString() { string output = "{"; for (int i = 0; i < this.length; i++) { if (i > 0) { output += ", "; } output += this.data[i]; } output += "}"; return output; } public void delete(int index) { for (int i = index; i < this.length - 1; i++) { this.data[i] = this.data[i+1]; } this.length--; resizeArrayIfNeeded(); } public void resizeArrayIfNeeded() { // Resize array if it is at full capacity if (length == size) { size *= 2; Object[] temp = new Object[size]; for (int i = 0; i < length; i++) { temp[i] = this.data[i]; } this.data = temp; } // Resize array if it is at less than 1/4 capacity if (length < size / 4) { size /= 2; Object[] temp = new Object[size]; for (int i = 0; i < length; i++) { temp[i] = this.data[i]; } this.data = temp; } } }
Editor Settings
Theme
Key bindings
Full width
Lines