您的位置:首页 > 其它

LeetCode 4

2018-03-15 21:30 21 查看

LeetCode 4

Median of Two Sorted ArraysCharacters

Problem Description:

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


Solution:

class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int> array;
int i = 0;
int j = 0;
while(i < nums1.size() && j < nums2.size()) {
if (nums1[i] <= nums2[j]) {
array.push_back(nums1[i]);
i++;
} else {
array.push_back(nums2[j]);
j++;
}
}
if (i >= nums1.size()) {
for (; j < nums2.size(); j++) {
array.push_back(nums2[j]);
}
} else if (j >= nums2.size()) {
for (; i < nums1.size(); i++) {
array.push_back(nums1[i]);
}
}
if (array.size() % 2) {
return array[array.size()/2]*1.0;
} else {
return (array[array.size()/2]+array[array.size()/2-1])/2.0;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 归并