LeetCode-4. Median of Two Sorted Arrays
2016-10-29 20:29
417 查看
1.问题描述
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:
Example 2:
2.算法思路
这道题是求两排列序列的中位数,并且要求了算法的时间复杂度,因为是两个排列的数列,所以当时很自然的想到了归并排序。
3.Java代码
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len1=nums1.length;
int len2=nums2.length;
int[] totalNum=new int[len1+len2];
len1--;
len2--;
int i=0;
while(len1>=0&&len2>=0){
if(nums1[len1]>nums2[len2])
totalNum[i++]=nums1[len1--];
else
totalNum[i++]=nums2[len2--];
}
while(len1>=0){
totalNum[i++]=nums1[len1--];
}
while(len2>=0){
totalNum[i++]=nums2[len2--];
}
int len=nums1.length+nums2.length;
if(len%2==0){
return (totalNum[len/2]+totalNum[len/2-1])/(float)2;
}
else{
return totalNum[len/2];
}
}
}PS:LeetCode的论坛里面提供了一种时间复杂度为O(log(min(m+n)))的算法,简单易懂,但是目前还没调出来。链接:https://discuss.leetcode.com/topic/4996/share-my-o-log-min-m-n-solution-with-explanation/52
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
2.算法思路
这道题是求两排列序列的中位数,并且要求了算法的时间复杂度,因为是两个排列的数列,所以当时很自然的想到了归并排序。
3.Java代码
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len1=nums1.length;
int len2=nums2.length;
int[] totalNum=new int[len1+len2];
len1--;
len2--;
int i=0;
while(len1>=0&&len2>=0){
if(nums1[len1]>nums2[len2])
totalNum[i++]=nums1[len1--];
else
totalNum[i++]=nums2[len2--];
}
while(len1>=0){
totalNum[i++]=nums1[len1--];
}
while(len2>=0){
totalNum[i++]=nums2[len2--];
}
int len=nums1.length+nums2.length;
if(len%2==0){
return (totalNum[len/2]+totalNum[len/2-1])/(float)2;
}
else{
return totalNum[len/2];
}
}
}PS:LeetCode的论坛里面提供了一种时间复杂度为O(log(min(m+n)))的算法,简单易懂,但是目前还没调出来。链接:https://discuss.leetcode.com/topic/4996/share-my-o-log-min-m-n-solution-with-explanation/52
相关文章推荐
- leetcode Median of Two Sorted Arrays
- [leetcode]Median of Two Sorted Arrays
- leetcode 26: Median of Two Sorted Arrays
- LeetCode: Median of Two Sorted Arrays
- LeetCode题目笔记(三) -- Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- [leetcode] Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays 解题报告
- LeetCode: Median of Two Sorted Arrays
- LeetCode刷题笔录 Median Of Two Sorted Arrays
- LeetCode Online Judge 题目C# 练习 - Median of Two Sorted Arrays
- leetCode_Median of Two Sorted Arrays
- LeetCode: Median of Two Sorted Arrays
- leetcode 26: Median of Two Sorted Arrays
- LeetCode Median of Two Sorted Arrays
- LeetCode-Median of Two Sorted Arrays
- Median of Two Sorted Arrays-----LeetCode
- [LeetCode题解004]Median of Two Sorted Arrays
- LeetCode —— Median of Two Sorted Arrays
- leetcode-004:Median of Two Sorted Arrays