Skip to content

Commit 4d1a355

Browse files
author
Partho Biswas
committed
670. Maximum Swap
1 parent 282e799 commit 4d1a355

File tree

2 files changed

+24
-31
lines changed

2 files changed

+24
-31
lines changed
Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,2 @@
11
import Foundation
2-
class Solution {
3-
func maximumSwap(_ num: Int) -> Int {
4-
var digits: [Int] = String(num).compactMap{ $0.wholeNumberValue }
5-
print("Digits: \(digits)")
6-
let sortedDigits: [Int] = digits.sorted {$0 > $1}
7-
print("Sorted: \(sortedDigits)")
8-
var numIdxMap = [Int:Int]()
9-
for (idx, item) in digits.enumerated() {
10-
numIdxMap[item] = idx
11-
}
12-
var swapIdx = 0
13-
while swapIdx < digits.count {
14-
if digits[swapIdx] != sortedDigits[swapIdx] {
15-
let targetIdx = numIdxMap[sortedDigits[swapIdx]]!
16-
print("targetIdx: \(targetIdx), swapIdx: \(targetIdx)")
17-
digits.swapAt(targetIdx, targetIdx)
18-
// (digits[swapIdx], digits[swapIdx]) = (digits[targetIdx], digits[swapIdx])
19-
break
20-
}
21-
}
22-
print("Digits: \(digits)")
23-
return Int(digits.reduce("") { $0 + String($1) }) ?? num
24-
}
25-
}
262

27-
/*
28-
29-
12345678
30-
*/

leetcode.com/swift/DS_ALGO_PRAC.playground/Sources/swift/670_Maximum_Swap.swift

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@ import Foundation
33
class Solution {
44
func maximumSwap(_ num: Int) -> Int {
55
var digits: [Int] = String(num).compactMap{ $0.wholeNumberValue }
6-
print("Digits: \(digits)")
76
let sortedDigits: [Int] = digits.sorted {$0 > $1}
8-
print("Sorted: \(sortedDigits)")
97
var numIdxMap = [Int:Int]()
108
for (idx, item) in digits.enumerated() {
119
numIdxMap[item] = idx
@@ -14,7 +12,6 @@ class Solution {
1412
while swapIdx < digits.count {
1513
if digits[swapIdx] != sortedDigits[swapIdx] {
1614
let targetIdx = numIdxMap[sortedDigits[swapIdx]]!
17-
print("targetIdx: \(targetIdx), swapIdx: \(swapIdx)")
1815
digits.swapAt(targetIdx, swapIdx)
1916
break
2017
}
@@ -23,3 +20,27 @@ class Solution {
2320
return Int(digits.reduce("") { $0 + String($1) }) ?? num
2421
}
2522
}
23+
24+
25+
26+
import Foundation
27+
// Time: O(n)
28+
class Solution {
29+
func maximumSwap(_ num: Int) -> Int {
30+
var digits: [Int] = String(num).compactMap{ $0.wholeNumberValue }
31+
var numIdxMap = [Int:Int]()
32+
for (idx, item) in digits.enumerated() {
33+
numIdxMap[item] = idx
34+
}
35+
36+
for currentIdx in 0..<digits.count {
37+
for numToSwapWith in stride(from: 9, to: digits[currentIdx], by: -1) {
38+
if let targetIdx = numIdxMap[numToSwapWith], targetIdx > currentIdx {
39+
digits.swapAt(currentIdx, targetIdx)
40+
return Int(digits.reduce("") { $0 + String($1) }) ?? num
41+
}
42+
}
43+
}
44+
return num
45+
}
46+
}

0 commit comments

Comments
 (0)