Swift Solution


  • 0

    var list: [Int] = []
    var hashMap: [Int:Int] = [:]

    func add(element: Int) {
        // If element is already present, then noting to do
        if let _ = hashMap[element] {
            return
        }
        
        //put element at the end of list
        list.append(element)
    
         //element is added as key and last array index as index.)
        hashMap.updateValue(list.count-1, forKey: element)
    }
    
    func remove(element: Int) {
        /* (1) Check if x is present by doing a hash map lookup.
           (2) If present, then find its index and remove it from hash map.
           (3) Swap the last element with this element in array and remove the last element.
           (4) Update index of last element in hash map. */
        
        //(1) Check if x is present by doing a hash map lookup.
        guard let elementeIndex = hashMap[element] else {
            return
        }
        
        //(2) If present, then find its index and remove it from hash map.
        hashMap.removeValue(forKey: element)
        
        //(3) Swap the last element with this element in array and remove the last element.
        list.swapAt(elementeIndex, list.count-1)
        //Remove last element (This is O(1))
        list.remove(at: list.count-1)
    
        //(4) Update index of last element in hash map. replace elementeIndex with new index (list.count-1) */
        hashMap.updateValue(list.count-1, forKey: elementeIndex)
    }
    
    func random() -> Int {
        // Find a random index from 0 to list count - 1
        let random = arc4random_uniform(UInt32(list.count))
        return list[Int(random)]
    }
    
    // Returns index of element if element is present, otherwise nil
    func search(element: Int) -> Int? {
        guard let index = hashMap[element] else {
            return nil
        }
        return index
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.