Array

`·2023년 4월 28일
0

1. Struture of Array

class MyArray {
  constructor () { 
    this.length = 0
    this.data = {}
  }
  get(index) {
    return this.data[index]
  }
  push (item) {
    this.data[this.length] = item
    this.length ++
    return this.length
  }
  pop() {
    const lastItem = this.data[this.length-1]
    delete this.data[this.length-1]
    this.length--
    return lastItem
  }
  delete(index) {
    const item = this.data[index]
    this.shiftItems(index)
    return lastItem
  }
  shiftItems(index) {
  
    for(let i = index; i < this.length -1; i ++) {
      this.data[i] = this.data[i+1]
    }
    delete this.data[this.length -1]
  }
}
const newArray = new MyArray()
newArray.push('1')
newArray.push('2')
newArray.push('3')
newArray.delete(1)
console.log(newArray)

2. Time Complexity

1) Static

  • lookup: O(1)
  • push: O(1)
  • insert: O(n)
  • delete: O(n)

2) Dynamic

  • lookup: O(1)
  • append: O(1) or O(n)
  • insert: O(n)
  • delete: O(n)

3. Pros & Cons

1) Props

  • Fast lookups
  • Fast push/pop
  • Ordered

2)Cons

  • Slow inserts
  • Slow deletes
  • Fixed size(if using static array)

0개의 댓글