從數組A中刪除在數組B中存在的元素,用C語言實現數組
考驗數組操做的能力,C語言的熟練程度。性能
1 //功能:從數組A中刪除在數組B中也存在的數據 2 //輸入:arrA --- 數組A 3 // lenA --- 數組A的長度 4 // arrB --- 數組B 5 // lenB --- 數組B的長度 6 //輸出:刪除後A的長度 7 int DelAwhichinB(int* arrA, int lenA, int* arrB, int lenB) 8 { 9 //int lenA = sizeof(arrA); //這裏是4,自動退化爲指針 10 11 int ndelcount = 0; //記錄有幾個被刪除 12 bool bsame = false; //是否存在相同的元素 13 int j=0; //刪除元素後的下標 14 15 for (int i=0; i<lenA; i++) 16 { 17 bsame = false; 18 for (int k=0; k<lenB; k++) 19 { 20 if (arrB[k] == arrA[i]) 21 { 22 ndelcount++; 23 bsame = true; 24 break; 25 } 26 } 27 28 if (false == bsame) 29 { 30 //若是在B中不存在,就放入新數組 31 arrA[j++] = arrA[i]; 32 } 33 } 34 35 return (lenA-ndelcount); 36 }
測試代碼:測試
1 int main(int argc, char* argv[]) 2 { 3 int arrA[9] = {7,2,5,9,10,23,67, 23, 11}; 4 //int arrB[3] = {4, 4, 4}; 5 int arrB[3] = {7, 5, 23}; 6 int arrlen = DelAwhichinB(arrA, 9, arrB, 3); 7 printf("刪除後的新數組是: "); 8 for (int i=0; i<arrlen; i++) 9 { 10 printf("%d ", arrA[i]); 11 } 12 }
測試結果:spa
以上是用最簡單,也最容易想到的辦法實現的,可能性能不是很好。但願提出改進建議,謝謝指針