MCPcopy Create free account
hub / github.com/Blankj/awesome-java-leetcode / Solution

Class Solution

src/com/blankj/hard/_0004/Solution.java:11–46  ·  view source on GitHub ↗

author: Blankj blog : http://blankj.com time : 2017/10/12 desc :

Source from the content-addressed store, hash-verified

9 * </pre>
10 */
11public class Solution {
12 public double findMedianSortedArrays(int[] nums1, int[] nums2) {
13 int len = nums1.length + nums2.length;
14 if (len % 2 == 0) {
15 return (helper(nums1, 0, nums2, 0, len / 2) + helper(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0;
16 }
17 return helper(nums1, 0, nums2, 0, (len + 1) / 2);
18 }
19
20 private int helper(int[] nums1, int m, int[] nums2, int n, int k) {
21 if (m >= nums1.length) return nums2[n + k - 1];
22 if (n >= nums2.length) return nums1[m + k - 1];
23 if (k == 1) return Math.min(nums1[m], nums2[n]);
24
25 int p1 = m + k / 2 - 1;
26 int p2 = n + k / 2 - 1;
27 int mid1 = p1 < nums1.length ? nums1[p1] : Integer.MAX_VALUE;
28 int mid2 = p2 < nums2.length ? nums2[p2] : Integer.MAX_VALUE;
29 if (mid1 < mid2) {
30 return helper(nums1, m + k / 2, nums2, n, k - k / 2);
31 }
32 return helper(nums1, m, nums2, n + k / 2, k - k / 2);
33 }
34
35 public static void main(String[] args) {
36 Solution solution = new Solution();
37 System.out.println(solution.findMedianSortedArrays(
38 new int[]{1, 3},
39 new int[]{2}
40 ));
41 System.out.println(solution.findMedianSortedArrays(
42 new int[]{1, 2},
43 new int[]{3, 4}
44 ));
45 }
46}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected