OneCoder Avatar
OneCodercoderli.com · 957 篇博文
🧮 Algo

数据结构与算法

双指针、回溯剪枝、图论与搜索

🎨 视觉封面

LeetCode[Algorithms] Median of Two Sorted Arrays

📅 2015-09-22·✍️ OneCoder·计算中...·⏱️ 6 分钟
#算法#LeetCode

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)).

{% highlight java %} package com.coderli.leetcode.algorithms;

/**

  • 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)).

  • @author li.hzh

  • @date 2015/9/6 10:42 */ public class MedianOfTwoSortedArrays {

    public static void main(String[] args) { Solution solution = new MedianOfTwoSortedArrays().new Solution(); int[] arrayOne = new int[]{1}; int[] arrayTwo = new int[]{}; System.out.println(solution.findMedianSortedArrays(arrayOne, arrayTwo)); }

    public class Solution {

    public double findMedianSortedArrays(int[] nums1, int[] nums2) { int lengthOne = nums1.length; int lengthTwo = nums2.length; int totalLength = lengthOne + lengthTwo; int mid = totalLength / 2; if (totalLength % 2 == 1) { return findKth(nums1, nums2, mid, 0, lengthOne - 1, 0, lengthTwo -1); } else { double one = findKth(nums1, nums2, mid, 0, lengthOne - 1, 0, lengthTwo -1); double two = findKth(nums1, nums2, mid - 1, 0, lengthOne - 1, 0, lengthTwo -1); return (one + two) / 2; } }

    private int findKth(int A[], int B[], int k, int aStart, int aEnd, int bStart, int bEnd) {

    Code 27 行
      int aLen = aEnd - aStart + 1;
      int bLen = bEnd - bStart + 1;
    
      if (aLen == 0)
         return B[bStart + k];
      if (bLen == 0)
         return A[aStart + k];
      if (k == 0)
         return A[aStart] < B[bStart] ? A[aStart] : B[bStart];
    
      int aMid = aLen * k / (aLen + bLen);
      int bMid = k - aMid - 1;
    
      aMid = aMid + aStart;
      bMid = bMid + bStart;
    
      if (A[aMid] > B[bMid]) {
         k = k - (bMid - bStart + 1);
         aEnd = aMid;
         bStart = bMid + 1;
      } else {
         k = k - (aMid - aStart + 1);
         bEnd = bMid;
         aStart = aMid + 1;
      }
    
      return findKth(A, B, k, aStart, aEnd, bStart, bEnd);
    

    } } } {% endhighlight %}

参考:http://www.programcreek.com/2012/12/leetcode-median-of-two-sorted-arrays-java/

💡 OneCoder 资源指引

所有代码开源上传至 GitHub:yummy-code 仓库 · GESP 专题站:GESP WIKI

🤝 技术交流与答疑

欢迎加入:C++ GESP/CSP 考级答疑群(688906745)Java/Python交流群(982860385),点击可直接加群。

📚

猜你想读 · 相关文章推荐

OneCoder

OneCoder (lihongzheshuai)

一个中年人的自留地,记录学习 C++、GESP/NOI、Java、Python 与算法架构的心得体会。本站唯一网址:coderli.com

读者讨论与留言

0 条讨论
✨ 支持点击留言直接回复 · Markdown 引用格式
💬 还没有读者留言,快来成为第一个讨论者吧!