• [LeetCode] Median of Two Sorted Arrays


    This link has a very concise and fast solution based on binary search. Spend some time reading it and make sure you understand it. It is very helpful. 

    Since the C++ interface of this problem has been updated, I rewrite the code below.

     1 class Solution {
     2 public:
     3     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
     4         int m = nums1.size(), n = nums2.size();
     5         if (m > n) return findMedianSortedArrays(nums2, nums1);
     6         int i, j, imin = 0, imax = m, half = (m + n + 1) / 2;
     7         while (imin <= imax) {
     8             i = (imin & imax) + ((imin ^ imax) >> 1);
     9             j = half - i;
    10             if (i > 0 && j < n && nums1[i - 1] > nums2[j]) imax = i - 1;
    11             else if (j > 0 && i < m && nums2[j - 1] > nums1[i]) imin = i + 1;
    12             else break;
    13         }
    14         int num1;
    15         if (!i) num1 = nums2[j - 1];
    16         else if (!j) num1 = nums1[i - 1];
    17         else num1 = max(nums1[i - 1], nums2[j - 1]);
    18         if ((m + n) & 1) return num1;
    19         int num2;
    20         if (i == m) num2 = nums2[j];
    21         else if (j == n) num2 = nums1[i];
    22         else num2 = min(nums1[i], nums2[j]);
    23         return (num1 + num2) / 2.0;
    24     }
    25 };
  • 相关阅读:
    Spring-Cloud之Feign
    Spring-Cloud之Ribbon原理剖析
    Spring-Cloud之Ribbon
    Spring-Cloud之Eureka
    显示列表
    顶点缓存对象(VBO)
    OpenGL观察轴
    OpenGL顶点数组
    OpenGL投影矩阵
    OpenGL变换
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4619941.html
Copyright © 2020-2023  润新知