kt: add «2460. Apply Operations to an Array»

URL:	https://leetcode.com/problems/apply-operations-to-an-array/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-03-01 13:52:50 +01:00
parent 49aed412b8
commit 18278624e8
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,28 @@
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
}
}