题目:Common coursesA teacher wants to compare the performance of two students. To understand them better, he’s looking at all the other courses they took, but it’s hard to spot the common courses just from a glance.
Given two arrays that contain the course IDs of two different students
Your task is to
- write a function that prints to standard output (stdout) all the course IDs that are contained in both arrays, sorted in ascending order, one per line
Note that your function will receive the following arguments:
- courses1
- which is the list of course IDs for the first student
- courses2
- which is the list of course ids for the second student
Data constraints
- the length of the array given as input will not exceed 1000 elements
Example
Input Output courses1: 1, 2, 8, 4, 5, 8, 3 courses2: 8, 2, 2, 7, 10
2 8
程序:#include <stdio.h>#include <stdlib.h>int compare ( const void * a , const void * b ) {return * ( int * ) a - * ( int * ) b ;}void get_common_courses ( int * courses1 , int courses1_length , int * courses2 , int courses2_length ) {int i , j ;qsort ( courses1 , courses1_length , sizeof ( int ), compare );qsort ( courses2 , courses2_length , sizeof ( int ), compare );for ( i = 0 , j = 0 ; i < courses1_length && j < courses2_length ; ) {if ( courses1 [ i ] == courses2 [ j ]) {int num = courses1 [ i ];printf ( "%d \n " , courses1 [ i ]);while ( courses1 [ ++ i ] == num );while ( courses2 [ ++ j ] == num );} else if ( courses1 [ i ] < courses2 [ j ]) {i ++ ;} else {j ++ ;}}}(程序来源@www.talentbuddy.co)之所以贴这个程序是因为我在做这一题的时候显示寻找两个数组的公共元素,然后把公共元素提取出来放在额外建好的数组里在进行排序处理,最后输出。但是显然我的想法比这个算法的时间和空间复杂度都要高,这是我应该学习的