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.
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: [1,0,0,2,3,0,0,4]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class DuplicateZeros {public static void main(String[] args) {int[] nums = { 1, 0, 2, 3, 0, 4, 5, 0 };duplicateZeros(nums);System.out.println(Arrays.toString(nums));}static void duplicateZeros(int[] arr) {int n = arr.length;List<Integer> res = new ArrayList<Integer>();for (int i = 0; i < n; i++) {if (arr[i] == 0) {res.add(0);if (res.size() == n) {for (int j = 0; j < arr.length; j++) {arr[j] = res.get(j);}break;} else {res.add(0);}if (res.size() == n) {for (int j = 0; j < arr.length; j++) {arr[j] = res.get(j);}break;}} else {res.add(arr[i]);if (res.size() == n) {{for (int j = 0; j < arr.length; j++) {arr[j] = res.get(j);}}break;}}}}}
C++
#include <bits/stdc++.h>using namespace std;void duplicateZeros(vector<int> &arr){int n = arr.size();vector<int> res;for (int i = 0; i < n; i++){if (arr[i] == 0){res.push_back(0);if (res.size() == n){arr = res;break;}else{res.push_back(0);}if (res.size() == n){arr = res;break;}}else{res.push_back(arr[i]);if (res.size() == n){arr = res;break;}}}}int main(){vector<int> nums = {1, 0, 2, 3, 0, 4, 5, 0};duplicateZeros(nums);cout << "[";for (int i = 0; i < nums.size() - 1; i++)cout << nums[i] << ",";cout << nums[nums.size() - 1] << "]";return 0;}
No comments:
Post a Comment