【Shawn-LeetCode】4.Median of Two Sorted Arrays
2017-06-05 14:12
323 查看
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:
Subscribe to see which companies asked this question.
题目是很简单,但是如果把复杂度控制在log(m+n)的范围内,肯定是有问题的,先贴一个超时的算法
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums3=new int[nums1.length+nums2.length];
System.arraycopy(nums1,0, nums3, 0, nums1.length);
System.arraycopy(nums2,0, nums3, nums1.length, nums2.length);
System.out.println(Arrays.toString(nums3));
Arrays.sort(nums3);
if(nums3.length%2==0){
return (nums3[nums3.length/2-1]+nums3[nums3.length/2])/2.0;
}
else return nums3[nums3.length/2];
}
}
正在探索新的方法
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
Subscribe to see which companies asked this question.
题目是很简单,但是如果把复杂度控制在log(m+n)的范围内,肯定是有问题的,先贴一个超时的算法
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums3=new int[nums1.length+nums2.length];
System.arraycopy(nums1,0, nums3, 0, nums1.length);
System.arraycopy(nums2,0, nums3, nums1.length, nums2.length);
System.out.println(Arrays.toString(nums3));
Arrays.sort(nums3);
if(nums3.length%2==0){
return (nums3[nums3.length/2-1]+nums3[nums3.length/2])/2.0;
}
else return nums3[nums3.length/2];
}
}
正在探索新的方法
相关文章推荐
- 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