C语言求一个编程题..已知一维数a中存放几个数据,试将下标为int(n/3)到int(n/2)元素删除。

留下您的代码吧大神.. 求放在VC里可运行的..

其实这个如果用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),这个就自己领悟吧,哈哈
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-06
首先,数组中的元素是不能删除的。
其次,数组是定了的。。你只能需要去除其中的元素,最好是用其他的,而是用后一个覆盖前一个的数据,最后的数据内容是加入一个‘0’的数据。
#include <stdio.h>
int main(void)
{
int a[7] = {1,2,3,4,5,6};
int i=0,temp,j;
for(i=0;i<sizeof(a)/4;i++){
temp = a[i];
if(temp%2==0 || temp %3 ==0){
for(j=i;j<sizeof(a)/4;j++)
a[j]=a[j+1];
}
}

puts("\n");
for(i=0;i<sizeof(a)/4;i++)
printf("%d\t",a[i]);
printf("\n");
return 0;
}
第2个回答  2013-05-06
n是什么?一维数组长度吗?暂时这么理解。
#include <stdio.h>
#define N 100
void main(){
//输入n个数,下标从0开始。删去下标从n/3到n/2(包括两端)的所有数,剩下的数组成一个一维数组
int a[N],n,i,j,delta;
printf("n=");
scanf("%d",&n);
printf("Input the numbers:");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
printf("Delete numbers from int(n/3) to int(n/2).\n");
delta=n/2-n/3+1;
i=n/3;
while(i+delta<=n){
a[i]=a[i+delta];
i++;
}
n-=delta;
printf("The new array:");
for(i=0;i<n;++i){
printf("%d ",a[i]);
}
}本回答被提问者采纳
相似回答