2 Solution1 in Swift


  • 0
    T

    1. Easy to understand:

    func missingNumber(_ nums: [Int]) -> Int {
        guard nums.count > 0 else {
            return (nums.first == 0) ? 1 : 0
        }
    
        let sortedNums = nums.sorted()
        var counter = 0
    
        for num in sortedNums {
            if num != counter {
                return counter
            }
    
            counter = counter + 1
        }
    
        return counter
    }
    

    2. Binary Search:

    func missingNumber(_ nums: [Int]) -> Int {
        guard nums.count > 0 else {
            return (nums.first == 0) ? 1 : 0
        }
    
        let sortedNums = nums.sorted()
    
        var left  = 0
        var right = sortedNums.count
        var mid   = (right - left) / 2 + left
    
        while left < right {
            mid = (right - left) / 2 + left
    
            if sortedNums[mid] > mid {
                right = mid
            } else {
                left = mid + 1
            }
        }
    
        return left
    }
    

Log in to reply
 

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