LeetCode 4. Median of Two Sorted Arrays(java)
2018-01-12 07:29
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)).
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
我的思路:把两个array merge以后再找中位数,时间O(M+N), 空间O(n+m). 第二段代码是early stop, 时间和空间都减半,但数量级不变。因为只需要找中位数,所以可以merge到一半就停下来。
代码一:
public double findMedianSortedArrays(int[] nums1, int[] nums2) { if (nums1 == null || nums2 == null) return -1; int n = nums1.length, m = nums2.length; int[] nums = new int[m + n]; int index1 = 0, index2 = 0, index = 0; while (index1 < nums1.length && index2 < nums2.length) { if (nums1[index1] > nums2[index2]) { nums[index++] = nums2[index2++]; } else { nums[index++] = nums1[index1++]; } } while (index1 < nums1.length) { nums[index++] = nums1[index1++]; } while (index2 < nums2.length) { nums[index++] = nums2[index2++]; } if (nums.length % 2 == 1) { return nums[nums.length / 2]; } else { double result = ((double)nums[nums.length / 2 - 1] + (double)nums[nums.length / 2]) / (double)2; return result; } }
代码二:
public double findMedianSortedArrays(int[] nums1, int[] nums2) { if (nums1 == null || nums2 == null) return -1; int n = nums1.length, m = nums2.length; int volumn = (m + n) / 2 + 1; int[] nums = new int[volumn]; int index1 = 0, index2 = 0, index = 0; while (index < volumn && index1 < nums1.length && index2 < nums2.length) { if (nums1[index1] > nums2[index2]) { nums[index++] = nums2[index2++]; } else { nums[index++] = nums1[index1++]; } } while (index < volumn && index1 < nums1.length) { nums[index++] = nums1[index1++]; } while (index < volumn && index2 < nums2.length) { nums[index++] = nums2[index2++]; } if ((m + n) % 2 == 1) { return nums[volumn - 1]; } else { double result = ((double)nums[volumn - 1] + (double)nums[volumn - 2]) / (double)2; return result; } }
相关文章推荐
- leetcode题解Java | 4. Median of Two Sorted Arrays
- leetcode:4. Median of Two Sorted Arrays(Java实现)
- Leetcode 4. Median of Two Sorted Arrays(java版)
- leetcode: 4. Median of Two Sorted Arrays (java)
- leetCode 4. Median of Two Sorted Arrays 解题思路和方法
- Leetcode 4. Median of Two Sorted Arrays[Hard]
- 【leetcode】4. Median of Two Sorted Arrays
- 【LeetCode】4. Median of Two Sorted Arrays
- LeetCode - 4. Median of Two Sorted Arrays : 逆推法 O(log(min(m,n))))
- LeetCode-4. Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays
- [LeetCode] 4. Median of Two Sorted Arrays ☆☆☆☆☆
- LeetCode 4. Median of Two Sorted Arrays
- [LeetCode]4. Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays的两种思路
- [leetcode] 4. Median of Two Sorted Arrays
- leetcode 4. Median of Two Sorted Arrays
- LeetCode-4. Median of Two Sorted Arrays
- 【LeetCode】4. Median of Two Sorted Arrays
- LeetCode题解:4. Median of Two Sorted Arrays