Skip to content

Commit 5e10a6f

Browse files
committed
2948. Make Lexicographically Smallest Array by Swapping Elements
1 parent 9406a4b commit 5e10a6f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
3+
// Solution by Sergey Leschev
4+
// 2948. Make Lexicographically Smallest Array by Swapping Elements
5+
6+
func lexicographicallySmallestArray(_ nums: [Int], _ limit: Int) -> [Int] {
7+
var nums = nums // Declare nums as a variable
8+
var b: [(Int, Int)] = []
9+
let n = nums.count
10+
11+
for i in 0..<n {
12+
b.append((nums[i], i))
13+
}
14+
15+
b.sort { $0.0 < $1.0 }
16+
var c: [[(Int, Int)]] = [b[0...0].map { $0 }]
17+
18+
for i in 1..<n {
19+
if b[i].0 - b[i - 1].0 <= limit {
20+
c[c.count - 1].append(b[i])
21+
} else {
22+
c.append([b[i]])
23+
}
24+
}
25+
26+
for t in c {
27+
var ind: [Int] = []
28+
for p in t {
29+
ind.append(p.1)
30+
}
31+
ind.sort()
32+
33+
for i in 0..<ind.count {
34+
nums[ind[i]] = t[i].0
35+
}
36+
}
37+
38+
return nums
39+
}
40+
}

0 commit comments

Comments
 (0)