Zhejiang University Edition "C Language Programming (3rd Edition)" question set: Exercise 7-4 Find elements that are not common to two arrays (20 points)

Given two integer arrays, this question requires finding elements that are not common to both.

Input format: The input provides two integer arrays in two lines. Each line first provides a positive integer N (≤20), followed by N integers, separated by spaces.
Output format: Output the elements that are not common to the two arrays in the order given by the numbers in one line. The numbers are separated by spaces, but there must be no extra spaces at the end of the line. The question guarantees that at least one such number exists. The same number is not output repeatedly.
Input example:

10 3 -5 2 8 0 3 5 -15 9 100
11 6 4 8 2 6 -5 9 0 100 8 1   

Output sample:

3 5 -15 6 4 1
#include<stdio.h>
//replace()函数的作用是对长度为n的a数组,删去下标为i的值
void replace(int a[], int n, int i) {
    
    
	for (int j = i; j < n-1; j++) {
    
    
		a[j] = a[j+1];
	}
}
int main(void) {
    
    
	int i, j, N1, N2, newN1, newN2;
	int num1[20], num2[20], dis[40], index = 0;
    //输入控制
	scanf("%d", &N1);
	for (i = 0; i < N1; i++) {
    
    
		scanf("%d", &num1[i]);
	}
	scanf("%d", &N2);
	for (i = 0; i < N2; i++) {
    
    
		scanf("%d", &num2[i]);
	}
	//newN1和newN2分别记录数组num1和数组num2去重后的数组长度值
	newN1 = N1;
	newN2 = N2;
	//去除num1数组中的重复值
	for (i = 0; i < newN1; i++) {
    
    
		for (j = i + 1; j < newN1; j++) {
    
    
			if (num1[i] == num1[j]) {
    
    
				replace(num1,newN1,j);
				newN1--;
			}
			
		}
	}
	//去除num2数组中的重复值
	for (i = 0; i < newN2; i++) {
    
    
		for (j = i + 1; j < newN2; j++) {
    
    
			if (num2[i] == num2[j]) {
    
    
				replace(num2,newN2,j);
				newN2--;
			}
		}
	}
	//找出num1数组中和num2数组的不同值
	for (i = 0; i < newN1; i++) {
    
    
		for (j = 0; j < newN2; j++) {
    
    
			if (num1[i] == num2[j]) {
    
    
				break;
			}
		}
		//运行到这里有两种可能的结果
		//一是因为循环结束
		//二是因为有相同的部分而break出来的
		//如果因为有相同而break出来的,表示对num1[i]而言在num2数组中没有相同的,用数组dis记录下来
		if (num1[i] != num2[j]) {
    
    
			dis[index++] = num1[i];
		}
	}
	//找出num2数组中和num1数组的不同值
	for (i = 0; i < newN2; i++) {
    
    
		for (j = 0; j < newN1; j++) {
    
    
			if (num2[i] == num1[j]) {
    
    
				break;
			}
		}
		if (num2[i] != num1[j]) {
    
    
			dis[index++] = num2[i];
		}
	}
	//输出结果
	for (i = 0; i < index - 1; i++) {
    
    
		printf("%d ", dis[i]);
	}
	printf("%d", dis[i]);
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43489041/article/details/105682028