【leetcode】4.Median of Two Sorted Arrays(c语言)

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)).
You may assume nums1 and nums2 cannot be both empty.

Example1:

nums1 = [1, 3]
nums2 = [2]

Example2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

[ 题目链接 ]

解题方法:
merge sort(归并排序)

double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){
	int* nums = (int*)malloc((nums1Size + nums2Size) * sizeof(int));
	double m;

	int i = 0, j = 0, k = 0;

	while (i < nums1Size&&j < nums2Size)
	{
		if (nums1[i] < nums2[j])
		{
			nums[k++] = nums1[i++];
		}
		else
		{
			nums[k++] = nums2[j++];
		}
	}

	//nums1还有一些数
	while (i < nums1Size)
		nums[k++] = nums1[i++];

	//nums2还有一些数
	while (j < nums2Size)
		nums[k++] = nums2[j++];

	//找到中位数并返回
	if ((nums1Size + nums2Size) % 2 == 0)
	{
		int pos = (nums1Size + nums2Size) / 2;
		m = (nums[pos] + nums[pos - 1]) / 2.0;
		return m;
	}
	else
	{
		int pos = (nums1Size + nums2Size) / 2;
		m = nums[pos];
		return m;
	}
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/82827693
今日推荐