数据结构与算法
双指针、回溯剪枝、图论与搜索
🎨 视觉封面LeetCode[Algorithms] Median of Two Sorted Arrays
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/
所有代码开源上传至 GitHub:yummy-code 仓库 · GESP 专题站:GESP WIKI
欢迎加入:C++ GESP/CSP 考级答疑群(688906745) 与 Java/Python交流群(982860385),点击可直接加群。
猜你想读 · 相关文章推荐
LeetCode[Algorithms] Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add...
LeetCode[Algorithms] Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcb...
LeetCode[Algorithms] Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers suc...
OneCoder (lihongzheshuai)
一个中年人的自留地,记录学习 C++、GESP/NOI、Java、Python 与算法架构的心得体会。本站唯一网址:coderli.com