一道水题

 
 
题目:
Common courses

A 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

InputOutput

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)
之所以贴这个程序是因为我在做这一题的时候显示寻找两个数组的公共元素,然后把公共元素提取出来放在额外建好的数组里
在进行排序处理,最后输出。但是显然我的想法比这个算法的时间和空间复杂度都要高,这是我应该学习的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值