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