// Two Pointers publicdoublefindMedianSortedArrays(int[] nums1, int[] nums2) { intm= nums1.length, n = nums2.length; intnumStep= (m + n - 1) / 2; // left-leaning (see the example above) intp1=0, p2 = 0; // Move to the first median for (inti=0; i < numStep; ++i) { // number of steps to move before it reaches a median if (p1 < m && p2 < n) { if (nums1[p1] < nums2[p2]) p1 += 1; else p2 += 1; } else { if (p1 < m) p1 += 1; else p2 += 1; } } // Calculate the median // If nums1[p1] < nums2[p2], we have nums1[p1] as the median / left part of median. // If nums1[p1] >= nums2[p2], we have nums2[p2] as the median / ... // If p1 >= m (out of bound), we have nums2[p2] as the median / ... // If p2 >= n (out of bound), we have nums1[p1] as the median / ... doublemedian=0; if (p1 < m && p2 < n) { // in bound if (nums1[p1] < nums2[p2]) median = nums1[p1++]; else median = nums2[p2++]; } else { // out of bound if (p1 < m) median = nums1[p1++]; else median = nums2[p2++]; } // Process even case (right part of the median) if ((m + n) % 2 == 0) { if (p1 < m && p2 < n) { median += (nums1[p1] < nums2[p2]) ? nums1[p1] : nums2[p2]; } else { if (p1 < m) median += nums1[p1]; else median += nums2[p2]; } median /= 2.0; } return median; }