1. /**
    2. * 4. Median of Two Sorted Arrays
    3. * <p>
    4. * Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
    5. * <p>
    6. * The overall run time complexity should be O(log (m+n)).
    7. * <p>
    8. * Example 1:
    9. * <p>
    10. * Input: nums1 = [1,3], nums2 = [2]
    11. * Output: 2.00000
    12. * Explanation: merged array = [1,2,3] and median is 2.
    13. * Example 2:
    14. * <p>
    15. * Input: nums1 = [1,2], nums2 = [3,4]
    16. * Output: 2.50000
    17. * Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
    18. * Example 3:
    19. * <p>
    20. * Input: nums1 = [0,0], nums2 = [0,0]
    21. * Output: 0.00000
    22. * Example 4:
    23. * <p>
    24. * Input: nums1 = [], nums2 = [1]
    25. * Output: 1.00000
    26. * Example 5:
    27. * <p>
    28. * Input: nums1 = [2], nums2 = []
    29. * Output: 2.00000
    30. * <p>
    31. * <p>
    32. * Constraints:
    33. * <p>
    34. * nums1.length == m
    35. * nums2.length == n
    36. * 0 <= m <= 1000
    37. * 0 <= n <= 1000
    38. * 1 <= m + n <= 2000
    39. * -106 <= nums1[i], nums2[i] <= 106
    40. */
    41. public class Lesson4 {
    42. public static void main(String[] args) {
    43. int[] nums1 = {1, 2};
    44. int[] nums2 = {3, 4};
    45. Util.println(new Solution().process(nums1, nums2));
    46. //System.out.println(new Solution().process(nums1, nums2));
    47. }
    48. private static class Solution {
    49. double process(int[] array1, int[] array2) {
    50. int[] arrayM = array1;
    51. int[] arrayN = array2;
    52. if (array1.length > array2.length) {
    53. arrayM = array2;
    54. arrayN = array1;
    55. }
    56. int m = arrayM.length;
    57. int n = arrayN.length;
    58. int min = 0;
    59. int max = m;
    60. int half = (m >> 1) + (n >> 1);
    61. while (min <= max) {
    62. int i = (min >> 1) + (max >> 1);
    63. int j = half - i;
    64. if (min < i && arrayM[i] < arrayN[j - 1]) {
    65. min = i + 1;
    66. } else if (i > min && arrayM[i - 1] > arrayN[j]) {
    67. max = i - 1;
    68. } else {
    69. int maxLeft = 0;
    70. if (i == 0) {
    71. maxLeft = arrayN[j - 1];
    72. } else if (j == 0) {
    73. maxLeft = arrayM[i - 1];
    74. } else {
    75. maxLeft = Math.max(arrayN[j - 1], arrayM[i - 1]);
    76. }
    77. if ((m + n) / 2 == 1) {
    78. return maxLeft + 0.0;
    79. }
    80. int minRight = 0;
    81. if (i == m) {
    82. minRight = arrayN[j];
    83. } else if (j == n) {
    84. minRight = arrayM[i];
    85. } else {
    86. minRight = Math.min(arrayN[j], arrayM[i]);
    87. }
    88. return (maxLeft + minRight) / 2.0;
    89. }
    90. }
    91. return 0.0;
    92. }
    93. }
    94. }