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:
parent
49aed412b8
commit
18278624e8
1 changed files with 28 additions and 0 deletions
28
kt/apply-operations-to-an-array.kt
Normal file
28
kt/apply-operations-to-an-array.kt
Normal 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
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue