11年408真题,pdf上给的参考答案竟然是错的,自己调了一遍
#include <stdio.h> #include <stdlib.h> int Search(int A[],int B[],int n); int main() { int a[5] = {3,12,13,14,15}; int b[5] = {2,4,6,8,20}; printf("%d", Search(a,b,5)); return 0; } int Search(int A[],int B[],int n) { int s1=0,d1=n-1,m1,s2=0,d2=n-1,m2; while(s1!=d1||s2!=d2) { m1=(s1+d1)/2; m2=(s2+d2)/2; printf("%d %d | %d %d ",s1,d1,s2,d2); delay(1000); if(A[m1]==B[m2]) return A[m1]; if(A[m1]<B[m2]) { if((s1+d1)%2==0) { s1=m1; d2=m2; } else { s1=m1+1; d2=m2; } } else { if((s1+d1)%2==0) { d1=m1; s2=m2; } else { d1=m1; s2=m2+1; } } } return A[s1]<B[s2]?A[s1]:B[s2]; }
时间复杂度O(log2n)
空间复杂度O(1)