1089. Duplicate Zeros

问题:

给定一个包含0的数组,对数组进行遇到0,则再输出一次,后续元素向后推移。

求的转换后的数组。

Example 1:
Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2:
Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3] 

Note:
1 <= arr.length <= 10000
0 <= arr[i] <= 9

  

解法:

数组是向后覆盖的,

因此从后往前,对数组进行覆盖赋值。才不会影响前面的元素。

发现规律:

从后往前的数字,如果不为0,那么位置都要向后推移,到当前数字为止0出现的次数。

如果为0,则向后推移:一次为包含自己0出现的次数,另一次为不包含自己0出现的次数。

 

因此,我们首先累计0出现的次数,

从后往前,进行上面的判断,进行数组赋值。

 

代码参考:

 1 class Solution {
 2 public:
 3     void duplicateZeros(vector<int>& arr) {
 4         int N=arr.size();
 5         int cout0=0;
 6         for(int a:arr){
 7             if(a==0)cout0++;
 8         }
 9         for(int i=N-1; i>=0 && cout0>=0; i--){
10             if(i+cout0<N){
11                 arr[i+cout0]=arr[i];
12             }
13             if(arr[i]==0){
14                 cout0--;
15                 if(i+cout0<N){
16                     arr[i+cout0]=arr[i];
17                 }
18             }
19         }
20         return;
21     }
22 };

 

posted @ 2020-06-20 15:59  habibah_chang  阅读(149)  评论(0编辑  收藏  举报