Point: binary seach, divide and conquer algorthim
I just give a timeout solution.
Title: Median of Two Sorted Arrays.
Description:
There are two sorted arrays nums1 and nums2 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)).
example:
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
Analysis:
My solution is merging two array into one.
one improved one is find the k-th number.listed below:
package com.connie;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Created by lenovo on 01/05/2019.
*/
public class medianofsortarray {
public static void main(String[] args) {
int[] arrayA = {1,6}, arrayB = {2, 4, 7};
System.out.println(Arrays.toString(mediansortarray(arrayA, arrayB)));
}
private static int [] mediansortarray(int[] arrayA, int[] arrayB) {
int a_length = arrayA.length;
int b_length = arrayB.length;
int N = a_length+b_length;
int[] array = new int[N];
int i = 0, j = 0, k = 0;
while(i <a_length && j <b_length) {
if(arrayA[i]<arrayB[j]) {
array[k++] = arrayA[i++];
} else {
array[k++] = arrayB[j++];
}
}
while(i != a_length) array[k++] = arrayA[i++];
while(j != b_length) array[k++] = arrayB[j++];
return array;
}
}
浙公网安备 33010602011771号