LC.P2460[对数组执行操作]

方法一:模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int[] applyOperations(int[] nums) {
int n = nums.length;
for (int i = 0; i < n - 1; ++i) {
if (nums[i] == nums[i + 1]) {
nums[i] *= 2;
nums[i + 1] = 0;
}
}
int k = 0;
for (int i = 0; i < n; ++i) {
if (nums[i] != 0) {
nums[k++] = nums[i];
}
}
for (int i = k; i < n; ++i) {
nums[i] = 0;
}
return nums;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$