It is known that the linear table A of length n adopts a sequential storage structure. Please write an algorithm with a time complexity of O(n) and a space complexity of O(1). This algorithm deletes all items whose values are in the linear table. data elements.
void Delete(ElemType A[ ],int n)
∥A是有n个元素的一维数组,本算法删除A中所有值为item的元素。
{i=1;j=n;∥设置数组低、高端指针(下标)。
while(i<j)
{while(i<j && A[i]!=item)i++; ∥若值不为item,左移指针。
if(i<j)while(i<j && A[j]==item)j--;∥若右端元素为item,指针左移
if(i<j)A[i++]=A[j--];}
It cannot run after rewriting. The following is the rewritten
package 线性表;
public class Work_10 {
public Work_10(){
int[] arr={2,34,4,4,5};
int item=4;
delete(arr,item,arr.length-1);
for(int a:arr){
System.out.print(a+" ");
}
}
public static void delete(int[] array,int item,int n){
int i=0,j=n;
while(i<j){
while(i<j&&array[i]!=item) i++;
if(i<j) while(i<j&&array[j]==item) j--;
if(i<j){
array[i++]=array[j--];
}
}
}
public static void main(String[] args) {
new Work_10();
}
}
Don’t know how to change it?
Please explain, sir
If you want to delete, search first, then delete. I will give you a search, and you can think of the rest and write a variant.
Oh, the extra number is because the number you output is wrong. The deletion process is fine.
Before deletion, the content of your array is
2,34,4,4,5
, a total of 5 elements.The content to be deleted is 4, which means that there are only 3 elements left after deletion, which are
2,34,5
So your result output only needs to output the first 3 elements of the array, and the last two are invalid elements.