题目:两个有序数组a和b,混合之,放在另一个数组c中,使得c也是有序数组(升序),去除重复的项。
虽然觉得不是很简便,但代码如下:
int merge_array (int *a , int *b, int *c, int n1, int n2) { if (n1 < 0 || n2 < 0) { return -1; } int i = 0; int j = 0; int k = 0; int count = 0; while (i < n1 && j < n2) { if (a[i] < b[j]) { if (k == 0) { c[k++] = a[i++]; count++; }else{ if (c[k-1] != a[i]) { c[k++] = a[i++]; count++; }else{ i++; } } }else if (a[i] == b[j]){ if (k == 0) { c[k++] = a[i++]; j++; count++; }else{ if (c[k-1] != a[i]) { c[k++] = a[i++]; j++; count++; }else{ i++; j++; } } }else{ if (k == 0) { c[k++] = b[j++]; count++; }else{ if (c[k-1] != b[j]) { c[k++] = b[j++]; count++; }else{ j++; } } } } while (i < n1) { if (k == 0) { c[k++] = a[i++]; count++; }else{ if (c[k-1] != a[i]) { c[k++] = a[i++]; count++; }else{ i++; } } } while (j < n2) { if (k == 0) { c[k++] = b[j++]; count++; }else{ if (c[k-1] != b[j]) { c[k++] = b[j++]; count++; }else{ j++; } } } return count; }
测试代码如下:
int a[1] = {1}; int b[1] = {2}; int c[100] = {0}; int count = merge_array(a, b, c, 1, 01); for (int i = 0; i < count; i++) { printf("c[%d] : %d\n", i, c[i]); }
测试多次,包括各种重复项、0项、负数项,运行都是正确的,欢迎大家提出更好的方法!
晚安。
时间: 2024-11-05 20:28:11