上一題:LeetCode第3題:lengthOfLongestSubstring(C語言)
思路:利用歸并排序的思想,將兩個數(shù)組合并為一個有序的數(shù)組,求中位數(shù)即可。
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
int total_count = nums1Size + nums2Size;
int sorted_nums[total_count];
int i = 0, j = 0, k = 0;
while((i < nums1Size) && (j < nums2Size)){
if(nums1[i] < nums2[j]){
sorted_nums[k] = nums1[i];
i++;
k++;
}
else{
sorted_nums[k] = nums2[j];
j++;
k++;
}
}
while(i < nums1Size){
sorted_nums[k++] = nums1[i++];
}
while(j < nums2Size){
sorted_nums[k++] = nums2[j++];
}
if(total_count % 2 == 1){
return sorted_nums[(total_count - 1) / 2];
}
double first = sorted_nums[(total_count - 1) / 2];
first = (first + sorted_nums[total_count / 2]) / 2;
return first;
}
本系列文章,旨在打造LeetCode題目解題方法,幫助和引導同學們開闊學習算法思路,由于個人能力和精力的局限性,也會參考其他網(wǎng)站的代碼和思路,如有侵權,請聯(lián)系本人刪除。
下一題:LeetCode第5題:longestPalindrome(C語言)