两个升序列的相同元素 代码(C)
本文地址: http://blog.csdn.net/caroline_wendy
两个升序列的相同元素, 需要使用两个指针, 依次遍历, 如果相等输出, 如果小于或大于, 则增加一个指针.
直到输出所有的值.
代码:
/* * main.cpp * * Created on: 2014.9.19 * Author: spike */ #include <stdio.h> int Common(int data1[], int length1, int data2[], int length2, int res[]) { if (data1 == NULL || length1 <= 0 || data2 == NULL || length2 <= 0) return -1; int i=0, j=0, k=0; while (i < length1 && j < length2) { if (data1[i] == data2[j]) { res[k++] = data1[i]; i++; j++; } else if (data1[i] < data2[j]) i++; else j++; } return k; } int main(void) { int data1[] = {1, 2, 4, 5, 6, 9, 11}; int data2[] = {2, 5, 6, 8, 12}; int length1 = sizeof(data1)/sizeof(data1[0]); int length2 = sizeof(data2)/sizeof(data2[0]); int max = length1 > length2 ? length1 : length2; int* res = new int[max]; int num = Common(data1, length1, data2, length2, res); for (int i=0; i<num; ++i) { printf("%d ", res[i]); } printf("\n"); return 0; }
输出:
2 5 6
时间: 2024-10-05 23:23:09