Swift using Set<Int>

  • 2

    Loop the array and put items in Set, every time removes the .min() one,
    yet maybe this runs nlogn time for min() and max()?

    class Solution {
       func thirdMax(_ nums: [Int]) -> Int {
    /* solution A: use Set<int> to check and keep 3 items, remove the min;*/
           var top3 = Set<Int>()
           for num in nums {
               if top3.count > 3 {
                   let min = top3.min() 
           return (top3.count == 3) ? top3.min()! : top3.max()!

Log in to reply

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