码迷,mamicode.com
首页 > 其他好文 > 详细

4. Median of Two Sorted Arrays

时间:2020-01-23 22:59:05      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:click   turn   empty   display   技术   amp   ||   ted   play   

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)).

You may assume nums1 and nums2 cannot be both empty.

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
技术图片
 1 class Solution {
 2     
 3     public double findMedianSortedArrays(int[] nums1, int[] nums2) {
 4         int m = nums1.length, n = nums2.length;
 5         int mid = (m + n) / 2 + (m + n) % 2;
 6         int pos1 = -1, pos2 = -1;
 7         while (mid > 0) {
 8             int temp = mid / 2 + mid % 2;
 9             if (pos2 + temp >= n || 
10                 (pos1 + temp < m && nums1[pos1 + temp] < nums2[pos2 + temp])) {
11                 pos1 += temp;
12             } else {
13                 pos2 += temp;
14             }
15             mid -= temp;
16         }
17         
18         
19         
20         double ans = 0;
21         if (pos2 == -1 || (pos1 != -1 && nums1[pos1] >= nums2[pos2])) {
22             ans = nums1[pos1];
23         } else {
24             ans = nums2[pos2];
25         }
26         if ((m + n) % 2 == 0) {
27             double  temp;
28             if (pos2 + 1 >= n || 
29                 (pos1 + 1 < m && nums1[pos1 + 1] < nums2[pos2 + 1]))
30                 temp = nums1[pos1 + 1];
31             else {
32                 temp = nums2[pos2 + 1];
33             }
34             ans = (ans + temp) / 2 ;
35         }
36         return ans;
37         
38     }
39 }
View Code

 

4. Median of Two Sorted Arrays

标签:click   turn   empty   display   技术   amp   ||   ted   play   

原文地址:https://www.cnblogs.com/hyxsolitude/p/12231538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!