LeetCode | 1089. Duplicate Zeros

it2022-05-05  198

 

题目:

Given a fixed length array arr of integers, 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, do not return anything from your function.

 

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 <= 100000 <= arr[i] <= 9

 

解题思路:

输入数组arr,要求将arr中的元素重新处理。如果arr[i] == 0,则将其右侧元素全部向右平移一个元素位置,空出的位置填0。例如:arr = 1, 0, 2, 3 则输出为 arr = 1, 0, 0, 2。多出的3元素则省略不保留。

 

代码:

class Solution { public: void duplicateZeros(vector<int>& arr) { if(arr.size() < 1) return; vector<int> back; for(int i = 0; i<arr.size(); i++) { back.push_back(arr[i]); if(arr[i] == 0) back.push_back(0); } arr.assign(back.begin(), back.begin()+arr.size()); return; } };

 

期望有另一种方法解了半个小时,然后用这个思路一遍AC了,coding真的很奇妙~

Runtime: 16 ms, faster than 97.92% of C++ online submissions for Duplicate Zeros.

Memory Usage: 9.6 MB, less than 100.00% of C++ online submissions for Duplicate Zeros.

 

晚安~

 

 

 


最新回复(0)