Skip to content

Commit f8f9ecc

Browse files
authored
Improved task 2948
1 parent 606aeda commit f8f9ecc

File tree

1 file changed

+11
-14
lines changed
  • src/main/kotlin/g2901_3000/s2948_make_lexicographically_smallest_array_by_swapping_elements

1 file changed

+11
-14
lines changed

src/main/kotlin/g2901_3000/s2948_make_lexicographically_smallest_array_by_swapping_elements/Solution.kt

+11-14
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,39 @@
11
package g2901_3000.s2948_make_lexicographically_smallest_array_by_swapping_elements
22

3-
// #Medium #Array #Sorting #Union_Find #2023_12_31_Time_2141_ms_(6.45%)_Space_69.2_MB_(74.19%)
3+
// #Medium #Array #Sorting #Union_Find #2023_12_31_Time_1831_ms_(6.45%)_Space_69.4_MB_(74.19%)
44

55
import kotlin.math.abs
66

77
class Solution {
88
fun lexicographicallySmallestArray(nums: IntArray, limit: Int): IntArray {
99
val n = nums.size
10-
val nodes = arrayOfNulls<Node>(n)
11-
for (i in 0 until n) {
12-
nodes[i] = Node(i, nums[i])
13-
}
14-
nodes.sortWith { a: Node?, b: Node? ->
10+
val nodes = Array(n) { i -> Node(i, nums[i]) }
11+
nodes.sortWith { a: Node, b: Node ->
1512
Integer.signum(
16-
a!!.value - b!!.value
13+
a.value - b.value
1714
)
1815
}
1916
var group = 1
20-
nodes[0]!!.group = group
17+
nodes[0].group = group
2118
for (i in 1 until n) {
22-
if (abs((nodes[i]!!.value - nodes[i - 1]!!.value).toDouble()) <= limit) {
23-
nodes[i]!!.group = group
19+
if (abs(nodes[i].value - nodes[i - 1].value) <= limit) {
20+
nodes[i].group = group
2421
} else {
25-
nodes[i]!!.group = ++group
22+
nodes[i].group = ++group
2623
}
2724
}
2825
val groupBase = IntArray(group + 1)
2926
for (i in n - 1 downTo 0) {
30-
groupBase[nodes[i]!!.group] = i
27+
groupBase[nodes[i].group] = i
3128
}
3229
val groupIndex = IntArray(n)
3330
for (node in nodes) {
34-
groupIndex[node!!.id] = node.group
31+
groupIndex[node.id] = node.group
3532
}
3633
val ans = IntArray(n)
3734
for (i in 0 until n) {
3835
val index = groupBase[groupIndex[i]]
39-
ans[i] = nodes[index]!!.value
36+
ans[i] = nodes[index].value
4037
groupBase[groupIndex[i]]++
4138
}
4239
return ans

0 commit comments

Comments
 (0)