同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。
题目为给定两个已排序之整数数组,请撰写程式回传两数组的中位数,如中位数有两个则回传两者之平均值。
题目与范例如下
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (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
Constraints:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
Follow up: The overall run time complexity should be O(log (m+n)).
我的策略为先计算中间值为两个整数或一个整数,并计算第一个中位数的位置。透过回圈依序取出两个整数数组中最小的值,当该值为中位数时,如中位数为两整数则储存于temp中,并于下次回圈中回传平均值,如中位数仅为单一数值则直接回传。
下方为我的代码
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){
int yn = (nums1Size + nums2Size) % 2;
short int middle = (nums1Size + nums2Size + 1)/2 -1;
short int listptr1 = 0,listptr2 = 0, counter = 0;
short int flag; // 1 = next num at nums1, 2 = next num at nums1
int tempnum = 0;
while(listptr1<nums1Size || listptr2<nums2Size){
if(listptr1 == nums1Size){
flag = 2;
}
else if(listptr2 == nums2Size){
flag = 1;
}
else{
if(nums1[listptr1] > nums2[listptr2]){
flag = 2;
}
else{
flag = 1;
}
}
if(counter == middle + 1){
switch(flag){
case 1 :
return (double) (nums1[listptr1] + tempnum)/2;
case 2 :
return (double) (nums2[listptr2] + tempnum)/2;
}
}
else if(counter == middle){
switch(yn){
case 0 :
switch(flag){
case 1 :
tempnum = nums1[listptr1];
listptr1 ++;
counter ++;
break;
case 2 :
tempnum = nums2[listptr2];
listptr2 ++;
counter ++;
break;
}
break;
case 1 :
switch(flag){
case 1 :
return (double) nums1[listptr1];
case 2 :
return (double) nums2[listptr2];
}
}
}
else{
switch(flag){
case 1 :
listptr1 ++;
counter ++;
break;
case 2 :
listptr2 ++;
counter ++;
break;
}
}
}
return 0;
}
yn 为判断几个中位数,1为一个中位数,2为两个中位数。
middle 为判断地一个中位数的位址 ( index ) ,listptr1 用来遍历 nums1 整数数组,listptr2 用来遍历 nums2 整数数组。
counter 用来判别已遍历的数量。
flag 判别此轮要取出之数字为 nums1 数组中的 ,或是 nums2 数组中的,1 为 nums1,2 为 nums2。
下方为时间与空间之消耗
Runtime: 4 ms, faster than 99.89% of C online submissions for Median of Two Sorted Arrays.
Memory Usage: 6.4 MB, less than 74.69% of C online submissions for Median of Two Sorted Arrays.
此次执行测试的次数比较多,进而发现同一份代码每次执行的时间与空间消耗其实都不相同,所以仅能当参考使用。