寫在前面:這裏是小王成長日誌,一名在校大學生,想在學習之餘將自己的學習筆記分享出來,記錄自己的成長軌跡,幫助可能需要的人。歡迎關注與留言。
題目:
題目鏈接:https://www.dotcpp.com/oj/problem1479.html
題目 1479: [藍橋杯][算法提高VIP]刪除數組中的0元素
時間限制: 1Sec 內存限制: 128MB 提交: 1463 解決: 922
題目描述
編寫函數CompactIntegers,刪除數組中所有值爲0的元素,其後元素向數組首端移動。注意,CompactIntegers函數需要接收數組及其元素個數作爲參數,函數返回值應爲刪除操作執行後數組的新元素個數。
輸入時首先讀入數組長度,再依次讀入每個元素。
將調用此函數後得到的數組和函數返回值輸出。
輸入
第一行一個數,表示數組個數
第二行爲每個數字,空格分開
輸出
輸出處理後的數字以及個數,各佔一行
樣例輸入
7
2 0 4 3 0 0 5
樣例輸出
2 4 3 5
4
C語言解法
#include <stdio.h>
int n;
int main(void)
{
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
int len = CompactIntegers(a, n);
for (int i = 0; i < len; i++)
printf("%d ", a[i]);
printf("\n%d", len);
return 0;
}
int judge(int *a, int i)
{
if (i == n - 1 && *(a + i) == 0)
return -1;
else if (*(a + i) == 0)
judge(a, i + 1);
else
return i;
}
int CompactIntegers(int *a, int len)
{
int tempin, temp, newlen = 0;
for (int i = 0; i < len; i++)
if (a[i] == 0)
{
tempin = judge(a, i);
newlen=i;
if (tempin == -1)
break;
temp = a[i];
a[i] = a[tempin];
a[tempin] = temp;
}
return newlen;
}
都看到這裏了,各位哥哥姐姐叔叔阿姨給小王點個贊 關個注 留個言吧,和小王一起成長吧,你們的關注是對我最大的支持。
有事沒事進來看看吧 : 小王的博客目錄索引
C語言專欄看這 : C語言學習專欄
如果以上內容有任何不準確或遺漏之處,或者你有更好的意見,就在下面留個言讓我知道吧-我會盡我所能來回答。