leetcode median of two sorted arrays

题目要求是

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log(m + n)). 

想法是类似于二分法,知道算法了之后的实现是容易的,值得注意的地方应该是数组处理中的个数问题。加加减减和条件判断,以及递归,需要小心。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <math.h>
 4 
 5 #define MAX 100
 6 int a[MAX];
 7 int b[MAX];
 8 int m;
 9 int n;
10 int k;
11 
12 void input(){
13     FILE* fp=fopen("/Users/vanellope/Desktop/1.txt","r");
14     fscanf(fp,"%d",&m);
15     fscanf(fp,"%d",&n);
16     fscanf(fp,"%d",&k);
17     for (int i=1;i<=m;i++){
18         fscanf(fp,"%d",&a[i]);
19        // printf("%d\n",a[i]);
20     }
21     for (int i=1;i<=n;i++){
22         fscanf(fp,"%d",&b[i]);
23         //printf("%d\n",b[i]);
24     }
25     fclose(fp);
26     return;
27 }
28 
29 int max(int x, int y){
30     if (x>y) return x;
31     else return y;
32 }
33 
34 int min(int x, int y){
35     if (x<y) return x;
36     else return y;
37 }
38 
39 void find(){
40     int i=1,j=1;
41     while(1){
42         if (i>m) {printf("%d\n",b[j+k-1]);break;}
43         if (j>n) {printf("%d\n",a[i+k-1]);break;}
44         if (k==1){
45             printf("%d\n",max(a[i],b[j]));
46             break;
47         }
48         int s=min(m,i+k/2-1), t=min(n,j+k/2-1);
49         if (a[s]>=b[t]){
50             k=k-(s-i+1);
51             i=s+1;
52             continue;
53         }
54         if (a[s]<b[t]){
55             k=k-(t-j+1);
56             j=t+1;
57             continue;
58         }
59     }
60 }
61 
62 int main(){
63     input();
64 //printf("1\n");
65     find();
66     return 0;
67 }
View Code

 

posted @ 2016-04-04 19:23  liyouvane  阅读(141)  评论(0)    收藏  举报