problem:
Give you a fixed-length array of integers arr
, each zero you the array are replication occurs again, and the remaining elements of pan right.
Note: Please do not write element in position over the length of the array.
Requirements: Please enter the array of the above modifications on the spot, do not return anything from a function.
Example 1:
Input: [1,0,2,3,0,4,5,0] Output: null explained: after the function call, the array input will be modified to: [1,0,0,2,3,0,0 , 4]
Example 2:
Input: [1,2,3] Output: null explained: after the function call, the array input will be modified to: [1,2,3]
prompt:
1 <= arr.length <= 10000
0 <= arr[i] <= 9
Links: https://leetcode-cn.com/contest/weekly-contest-141/problems/duplicate-zeros/
analysis:
Do not write more than is required in the position of the element array length, you can traverse again, experiencing zero will erase the last one, and then insert a 0 at the current position.
AC Code:
1 class Solution { 2 public: 3 void duplicateZeros(vector<int>& arr) { 4 int length = arr.size(); 5 for (int i = 0; i < length; i++) 6 { 7 if (arr[i] == 0) 8 { 9 arr.erase(arr.end()-1); 10 arr.insert(arr.begin()+i, 0); 11 i++; 12 } 13 } 14 } 15 };
other:
1. The first code
1 class Solution { 2 public void duplicateZeros(int[] arr) { 3 int n = arr.length; 4 int[] a = Arrays.copyOf(arr, n); 5 int p = 0; 6 for(int i = 0;i < n;i++){ 7 if(a[i] == 0){ 8 if(p < n)arr[p++] = 0; 9 if(p < n)arr[p++] = 0; 10 }else{ 11 if(p < n)arr[p++] = a[i]; 12 } 13 } 14 } 15 }
Construction backup input data, and modify the original position.
2, vector remove elements erase,
vector<int> vec;
vec.erase (vec.begin () + index); // delete vec [index] Data
vec.insert (vec.begin () + index, value); // value is inserted in position index.