Finding the second smallest integer in array

后端 未结 19 2293
無奈伤痛
無奈伤痛 2021-01-18 05:48

We are required in our assignment to find the second smallest integer in one array recursively. However, for the sake of understanding the subject more, I want to do it iter

19条回答
  •  太阳男子
    2021-01-18 06:23

    Here's a Swift version that runs in linear time. Basically, find the smallest number. Then assign the 2nd minimum number as the largest value. Then loop through through the array and find a number greater than the smallest one but also smaller than the 2nd smallest found so far.

    func findSecondMinimumElementLinear(in nums: [Int]) -> Int? {
        // If the size is less than 2, then returl nil.
        guard nums.count > 1 else { return nil }
    
        // First, convert it into a set to reduce duplicates.
        let uniqueNums = Array(Set(nums))
    
        // There is no point in sorting if all the elements were the same since it will only leave 1 element
        // after the set removed duplicates.
        if uniqueNums.count == 1 { return nil }
    
        let min: Int = uniqueNums.min() ?? 0 // O(n)
        var secondMinNum: Int = uniqueNums.max() ?? 0 // O(n)
        // O(n)
        for num in uniqueNums {
            if num > min && num < secondMinNum {
                secondMinNum = num
            }
        }
    
        return secondMinNum
    }
    

提交回复
热议问题