Given a fixed length array
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.
Solution in C++:
void duplicateZeros(vector<int>& arr) {
int i = 0;
int iter = 0;
//Calculating the index before which array get terminated
for(iter = 0; iter < arr.size(); ++i){
//Case: If the digit is zero then increase by two
if(arr.at(i) == 0){
iter = iter + 2;
} else {
++iter;
}
}
--i;
bool is_zero_only_once = false;
if((iter > arr.size()) && (arr.at(i) == 0)){
is_zero_only_once = true;
}
for(auto idx = arr.rbegin(); idx != arr.rend(); ++idx){
if(arr.at(i) == 0){
*idx = 0;
if(is_zero_only_once == true){
is_zero_only_once = false;
--i;
continue;
}
++idx;
if(idx == arr.rend()){
return;
}
*idx = 0;
} else {
*idx = arr.at(i);
}
--i;
}
}
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.
Solution in C++:
void duplicateZeros(vector<int>& arr) {
int i = 0;
int iter = 0;
//Calculating the index before which array get terminated
for(iter = 0; iter < arr.size(); ++i){
//Case: If the digit is zero then increase by two
if(arr.at(i) == 0){
iter = iter + 2;
} else {
++iter;
}
}
--i;
bool is_zero_only_once = false;
if((iter > arr.size()) && (arr.at(i) == 0)){
is_zero_only_once = true;
}
for(auto idx = arr.rbegin(); idx != arr.rend(); ++idx){
if(arr.at(i) == 0){
*idx = 0;
if(is_zero_only_once == true){
is_zero_only_once = false;
--i;
continue;
}
++idx;
if(idx == arr.rend()){
return;
}
*idx = 0;
} else {
*idx = arr.at(i);
}
--i;
}
}
Comments
Post a Comment