其实这个如果用C++的话,很简单的,用stl里的容器vector很容易就实现了,C语言库中没有容器这个概念,下面就给出具体实现代码吧(用数组实现)。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
/**
* Description:
* Delete items from index start to end of an array.
* @para: a -- the array, n -- the lenght of the array,
* start -- the start index of the array to delete
* end -- the end index of the array to delete
*/
void deleteItemFromArray(int a[], int& n, int start, int end)
//因为删除了元素会改变数组的大小,因此在这里将参数n按引用传递,以操作完成后改变n的大小
//该函数能删除任意区间(在数组的大小范围内)的数
{
int i, j;
for (i = start, j = 1; j + end <= n; i++, j++)
{
a[i] = a[end + j];
}
n = n - (end - start + 1);
}
int main()
{
int n = 10, i, a[15];
//随机产生n个数
srand(time(0));//设置随机种子
for (i = 0; i < n; i++)
a[i] = rand() % 100;//随机数的范围为0-99
printf ("Before deleting numbers, the numbers in array is: \n");
for (i = 0; i < n; i++)
printf ("%d ", a[i]);
printf ("\n");
int start = n / 3;
int end = n / 2;
deleteItemFromArray(a, n, start, end);//delete numbers
printf ("After deleting numbers, the numbers in array is: \n");
for (i = 0; i < n; i++)
printf ("%d ", a[i]);
printf ("\n");
return 0;
}
时间复杂度为O(n), 已经通过测试,但有个缺点是如果n很大,需要移动的次数就会很大,效率比较低,如果用链表实现的话,时间复杂度能达到O(1),这个就自己领悟吧,哈哈
温馨提示:答案为网友推荐,仅供参考