前言
记录PTA
一、题目?
比赛成绩中“去掉一个最高分,去掉一个最低分”常有。编写函数,对传入的指定长度的指定数组进行去最值处理(去掉一个最大和一个最小值,其它元素保持相对不变),删除最值时需要移动元素(后边的元素要前移),要求采用高效算法:移动元素尽量少的元素,因为最大最小值是两个,故原来的数组长度自然是减少了两个,主调函数自知,你不用返回删除后的长度,但是,要求删除函数返回总的移动次数(以测试你是不是以最少的移动完成)。
函数接口定义:
int delMaxMin(int A[],int n);
删除最值后的值仍存储于原数组。 n是数组的实际长度,程序保证n>2。函数返回删除最大与最小值时移动的元素个数。
输入样例:
第一行是数组的长度,第二行是空格分隔的数组元素。如:
10
9 3 8 3 3 9 8 5 8 8
结尾无空行
输出样例:
你只需要完成删除最值的函数(返回移动元素个数),输出由测试程序完成:第一行去最值后的数组,第二行,移动的元素个数。
{9,3,8,3,8,5,8,8}
4
结尾无空行
/* 请在这里填写答案 */
二、答案
int move(int* arr,int start,int last,int move_cnt);
int delMaxMin(int A[],int n)
{
int flag = 0;
int cnt = 0,index_max = 0,index_min = 0;
int max = A[0],min = A[0];
// 找最大最小值
for(int i=1;i<n;i++){
if( max<=A[i] ){
max = A[i];
index_max = i;
}
if( min>=A[i] ){
min = A[i];
index_min = i;
}
}
// 保证 最大值的下标一定是最后的
if( index_max < index_min )
{
int temp = index_max;
index_max = index_min;
index_min = temp;
}
cnt = move(A,index_min+1,index_max,1);
cnt += move(A,index_max+1,n,2);
return cnt;
}
int move(int* arr,int start,int last,int move_cnt)
{
int cnt = 0;
for(int i=start;i<last;i++)
{
arr[i-move_cnt] = arr[i];
cnt++;
}
return cnt;
}