Leet Code OJ 4. Median of Two Sorted Arrays [Difficulty: Hard]
生活随笔
收集整理的這篇文章主要介紹了
Leet Code OJ 4. Median of Two Sorted Arrays [Difficulty: Hard]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
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.0Example 2:
nums1 = [1, 2] nums2 = [3, 4]The median is (2 + 3)/2 = 2.5翻譯
有2個排序過的數組nums1,nums2,它們的長度分別是m和n。
找到兩個數組的中位數,總的運行時間需要是 O(log (m+n))。
例1:
例2:
nums1 = [1, 2] nums2 = [3, 4]中位數: (2 + 3)/2 = 2.5分析
以下解法LeetCode時間為65ms,雖然Accepted了,但時間復雜度沒到O(log (m+n)),該解法待后續優化。
Java版代碼(時間復雜度O(m+n),空間復雜度O(m+n)):
public class Solution {public double findMedianSortedArrays(int[] nums1, int[] nums2) {if (nums1.length == 0 && nums2.length == 0) {return 0.0;} else if (nums1.length == 0) {return getMid(nums2);} else if (nums2.length == 0) {return getMid(nums1);}Double mid1 = getMid(nums1), mid2 = getMid(nums2);int len = nums1.length + nums2.length;int index1 = len / 2, index2 = len / 2;if (len % 2 == 0) index1--;int sum = 0, current, j = 0, k = 0;if (mid1 < mid2) {j = nums1.length < 2 ? 0 : nums1.length / 2 - 1;} else {k = nums2.length < 2 ? 0 : nums2.length / 2 - 1;}for (int i = j + k; i < len; i++) {if (j >= nums1.length) {if (sum == 0) {sum = nums2[index1 - nums1.length];}return (sum + nums2[index2 - nums1.length]) / 2.0;} else if (k >= nums2.length) {if (sum == 0) {sum = nums1[index1 - nums2.length];}return (sum + nums1[index2 - nums2.length]) / 2.0;}if (nums1[j] < nums2[k]) {current = nums1[j];j++;} else {current = nums2[k];k++;}if (i == index1) {if (index1 == index2) {return current;}sum = current;}if (i == index2) {sum += current;return sum / 2.0;}}return 0;}public Double getMid(int n[]) {int len = n.length;if (len == 0) {return null;}if (len % 2 == 0) {return (n[len / 2 - 1] + n[len / 2]) / 2.0;} else {return n[len / 2] / 1.0;}} }總結
以上是生活随笔為你收集整理的Leet Code OJ 4. Median of Two Sorted Arrays [Difficulty: Hard]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 388. Lo
- 下一篇: Leet Code OJ 3. Long