In: Computer Science
Implement the earse one() function by using the array shifting method (i.e., remove one target item and shift all right items one position left).
This Question can be easily done with the help of an another array. Following is the algorithm for the solution followed by it's implimentation using Java program:
Algorithm:
Step 1 : Create temporary array of length same as that of original array
Step 2: Initialize counter variable to 0
Step 3: Traverse the array using for loop till length starting from 0
Step 4 : If i'th element does not match with the target number, add this number to temporary array
Step 5: Step 4 will be repeated up until n times i.e till the size
Step 6: Print temporary array
Program :
public void erase_one(int arr[],int target){
int temp[] = new int[arr.length];
int x=0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]!=target){
temp[x] = arr[i];
x++;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(temp[i]+" ");
}
}