如何删除数组中找到的元素并将数组元素移到左侧?
int search(int a[]) { int i,V,index; printf("Enter the element (V),That you want to find:>"); scanf("%d",&V); for (i=0;i<N;i++) { if(a[i]==V) { V=a[i]; index=i; } } printf("%d is located in a[%d].",V,index )
如果您不关心元素的排序,可以在O(1)时间内删除找到的元素。
// Find the element you're looking for. int index = find(A, V); // Stuff the last element into the index found. A[index] = A[N-1]; // Reduce the total number of elements. N--;
如果我需要将所有内容移到数组中,我会小心地使用memmove()
。 然后用0或其他适当的值消除空出的元素。
if (index < N-1) memmove(&a[index], &a[index+1], ((N-1)-index) * sizeof(a[0])); array[N-1] = 0;
无法调整C数组的大小,因此如果不创建新数组,则无法执行此操作。 您可以实施的一些建议:
-
通过具有第二个
deleted
bool数组或将项目设置为某个未使用的值(例如-1),将项目标记为已删除(延迟删除)。 -
使用向量,但这不再是C。 STL向量具有
erase()
方法。 -
向量的删除效率很低,因此根据您执行的其他操作,您可以使用
deque
。 再次,这将成为C ++,但您也可以在deque
上使用erase()
。
也许使用链表,二叉树或其他数据结构,允许您快速搜索和删除包含目标数据的节点。