Swift solution - Bucket Sort, Hash Table


  • 0
    class Solution {
        func hIndex_Sort(_ citations: [Int]) -> Int {
            let n = citations.count
            var buckets = [Int](repeatElement(0, count: n + 1))
            var count = 0
            
            for citation in citations {
                if citation > n {
                    buckets[n] += 1
                } else {
                    buckets[citation] += 1
                }
            }
            for i in stride(from: n, through: 0, by: -1) {
                count += buckets[i]
                if count >= i {
                    return i
                }
            }
            
            return 0
        }
        
        func hIndex_HashTable(_ citations: [Int]) -> Int {
            var map = [Int: Int]()
            var h = 0
            
            for citation in citations {
                if citation > h {
                    if (map[h] ?? 0) != 0 {
                        map[h] = (map[h] ?? 0) - 1
                    } else {
                        h += 1
                    }
                    map[citation] = (map[citation] ?? 0) + 1
                }
            }
            
            return h
        }
    }
    

Log in to reply
 

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