Topic describes
Given two positive-ordered (from small to large) arrays of size m and n, nums1 and nums2. Please find and return the median of the two positive ordinal groups.
The sample
Example 1: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: Merge array = [1,2,3], median 2
Example 2: input: nums1 = [1,2], nums2 = [3,4] output: 2.50000 description: merge array = [1,2,3,4], median (2 + 3) / 2 = 2.5
Example 3: input nums1 = [0,0], nums2 = [0,0] output 0.00000
Example 4: Input nums1 = [], nums2 = [1] Output 1.00000
Example 5: Input nums1 = [2], nums2 = [] Output 2.00000
Tip: nums1.length == m nums2.length == n 0 <= m <= 1000 0 <= n <= 1000 1 <= m + n <= 2000 -106 <= nums1[i], nums2[i] <= 106
Source: LeetCode link: leetcode-cn.com/problems/me…
implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size)
{
int v = 0; // Marks the subscript of the new array
int nums3[nums1Size + nums2Size];
int result = 0;
int i = 0;
int j = 0;
if (nums1 == NULL && nums2 == NULL) {
return 0.0;
}
for (i = 0, j = 0; i < nums1Size && j < nums2Size;) {
if (nums1[i] >= nums2[j]) {
nums3[v++] = nums2[j++];
} else{ nums3[v++] = nums1[i++]; }}if (i < nums1Size) {
while(i < nums1Size) { nums3[v++] = nums1[i++]; }}if (j < nums2Size) {
while(j < nums2Size) { nums3[v++] = nums2[j++]; }}if ((nums1Size + nums2Size) % 2= =0) {
return ((nums3[(nums1Size + nums2Size) / 2 - 1]) + nums3[(nums1Size + nums2Size) / 2) /2.0;
} else {
return nums3[(nums1Size + nums2Size) / 2];
}
return 1.0;
}
Copy the code