LeetCode - Median of Two Sorted Arrays
Posted IncredibleThings
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode - 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)). Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
题目要求time complexity 是O(log (m+n)), 先归并排序也是不可行的, 时间复杂度为O(m+n)
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int l1 = nums1.length; int l2 = nums2.length; int i1 = 0; int i2 = 0; int i = 0; int[] nums = new int[l1+l2]; while(i1 < l1 && i2 <l2){ int num1 = nums1[i1]; int num2 = nums2[i2]; if(num1 < num2){ nums[i] = num1; i1++; } else{ nums[i] = num2; i2++; } i++; } if(i1 == l1){ while(i2 < l2){ nums[i]=nums2[i2]; i2++; i++; } } else if(i2 == l2){ while(i1 <l1){ nums[i] = nums1[i1]; i1++; i++; } } //find median if(i % 2 != 0){ return (double)nums[i/2]; } else{ return ((double)nums[i/2-1] + (double)nums[i/2])/2; } } }
以上是关于LeetCode - Median of Two Sorted Arrays的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 4. Median of Two Sorted Arrays
LeetCode: Median of Two Sorted Arrays
Leetcode 4. Median of Two Sorted Arrays(二分)
LeetCode题解-----Median of Two Sorted Arrays