1089 Duplicate Zeros
Given a fixed-length integer array arr
, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.
Example 1:
Example 2:
Constraints:
1 <= arr.length <= 104
0 <= arr[i] <= 9
这题,如果可以用额外空间的话,很容易。但是,要S: O(1)的话,比较麻烦。一开始就想到了,数0,因为每个0会+2,所以只要数下标数到超过原arr长度就ok了。然后从后到前copy,见到0就copy 2个。但是有一个edge case想不通怎么特判掉,[0, 0, 1]的时候,最后一个0其实是不用dup的。后来看了solution改良了一下自己的想法,用一个boolean判断掉。如果break的时候下标刚好等于的话,是可以dup的,如果大于,就表示最后一个0不用dup。
Previous1855 Maximum Distance Between a Pair of ValuesNext2511 Maximum Enemy Forts That Can Be Captured
Last updated