Simple and fast Swift solution


  • 0
    A
    class Solution {
        func maximumSwap(_ num: Int) -> Int {
            var digits = Array(String(num).characters).map { Int(String($0))!}
            for (idx, d) in digits.enumerated() {
                var idx2 = idx + 1
                var max = d + 1
                var maxIdx = -1
                while idx2 < digits.count {
                    if digits[idx2] >= max {
                        max = digits[idx2]
                        maxIdx = idx2
                    }
                    idx2 += 1
                }
                if maxIdx >= 0 {
                    swap(&digits[maxIdx], &digits[idx])
                    return digits.reduce(0, { r, d in r * 10 + d })
                }
            }
            return num
        }
    }

Log in to reply
 

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