Skip to content

Commit 76ec0bc

Browse files
add 2460
1 parent b60a50b commit 76ec0bc

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,37 @@ fun sortArrayByParityII(nums: IntArray): IntArray {
6262
return nums
6363
}
6464

65+
/**
66+
* 2460. Apply Operations to an Array
67+
*/
68+
69+
fun applyOperations(nums: IntArray): IntArray {
70+
for (i in 0 until nums.size - 1) {
71+
if (nums[i] == nums[i + 1]) {
72+
nums[i] *= 2
73+
nums[i + 1] = 0
74+
}
75+
}
76+
var i = 0
77+
var j = 1
78+
while (i < nums.size && j < nums.size) {
79+
while (i < nums.size && nums[i] != 0) i++
80+
j = i
81+
while (j < nums.size && nums[j] == 0) j++
82+
if (i < nums.size && j < nums.size) {
83+
nums.swap(i, j)
84+
i++
85+
j++
86+
}
87+
}
88+
89+
return nums
90+
}
91+
92+
private fun IntArray.swap(from: Int, to: Int) {
93+
val temp = this[from]
94+
this[from] = this[to]
95+
this[to] = temp
96+
}
97+
6598

0 commit comments

Comments
 (0)