URL: https://leetcode.com/problems/apply-operations-to-an-array/ Signed-off-by: Matej Focko <me@mfocko.xyz>
28 lines
636 B
Kotlin
28 lines
636 B
Kotlin
class Solution {
|
|
fun applyOperations(nums: IntArray): IntArray {
|
|
val n = nums.size
|
|
|
|
var nonZero = 0
|
|
nums.indices.forEach { i ->
|
|
if (i < n - 1 && nums[i] != 0 && nums[i] == nums[i + 1]) {
|
|
nums[i] *= 2
|
|
nums[i + 1] = 0
|
|
}
|
|
|
|
if (nums[i] == 0) {
|
|
return@forEach
|
|
}
|
|
|
|
if (i != nonZero) {
|
|
(nums[nonZero] to nums[i]).let { (x, y) ->
|
|
nums[i] = x
|
|
nums[nonZero] = y
|
|
}
|
|
}
|
|
|
|
nonZero++
|
|
}
|
|
|
|
return nums
|
|
}
|
|
}
|