评论

收藏

[C++] Median of Two Sorted Arrays

编程语言 编程语言 发布于:2021-08-07 12:51 | 阅读数:510 | 评论:0

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)).
题意
长度为m和n排好序的数组A和B,找出A和B的中值
思路
将A和B放到数组C中排好序,找出C中的中间值。如果C的长度为奇数,返回C[C.length / 2] / 2;如果C长度为偶数,返回中间两个数的平均值,返回(C[size / 2] + C[(size - 1)/ 2]) / 2
1 public class Solution {
 2   public double findMedianSortedArrays(int A[], int B[]) {
 3     double C[] = new double[A.length + B.length];
 4     int ptr_a = 0;
 5     int ptr_b = 0;
 6     int ptr_c = 0;
 7     for(; ptr_a < A.length && ptr_b < B.length && ptr_c < C.length; ptr_c++){
 8       if(A[ptr_a] > B[ptr_b]){
 9         C[ptr_c] = B[ptr_b];
10         ptr_b++;
11       }
12       else{
13         C[ptr_c] = A[ptr_a];
14         ptr_a++;
15       }
16     }//for
17     while(ptr_a < A.length)
18     {
19       C[ptr_c++] = A[ptr_a++];
20     }
21     while(ptr_b < B.length)
22     {
23       C[ptr_c++] = B[ptr_b++];
24     }
25 
26     
27 
28     int size = C.length;
29     if(size % 2 == 1)
30       return C[size / 2];
31     return (C[size / 2] + C[(size - 1)/ 2]) / 2;  
32   }
33 }


关注下面的标签,发现更多相似文章