leetcode median of two sorted arrays C語言實現

C語言實現思路數組

  1. 合併兩個給出的數組
  2. 將合併後的數組按照從小到大的順序進行排列
  3. 半段n1+n2個數的奇偶性
  4. 找到中指
#include <stdio.h>
int Odd(int n);
void orderIntegerArray(int *p, int n);
double findMedianSortedArrays(int *numS1, int n1, int *sumS2, int n2);
int main(void)
{
    int nums1[9] = {3, 13, 7, 5, 21, 23, 23, 40, 23};
    int nums2[5] = {14, 12, 56, 23, 29};
    printf("The median is %lf\n", findMedianSortedArrays(nums1, 9, nums2, 5));

    return 0;
}

double findMedianSortedArrays(int *numS1, int n1, int *numS2, int n2)
{
    int *p, *q;
    p = numS1;
    q = numS2;
    int newArray[n1 + n2];
    int *k;
    k = newArray;
    for (int i = 0; i < n1; i++)
        *(k + i) = *(p + i);
    for (int i = n1; i < n1 + n2; i++)
        *(k + i) = *(q + i - n1);
    orderIntegerArray(newArray, n1 + n2);
    for (int i = 0; i < n1 + n2; i++)
        printf("%d---", *(k + i));
    putchar('\n');
    double median;
    int n3 = n1 + n2;
    if (Odd(n3))
        median = newArray[(n3 + 1) / 2 - 1];
    else
        median = (newArray[n3 / 2 - 1] + newArray[n3 / 2 + 1 - 1]) / 2;
    return median;
}

void orderIntegerArray(int *p, int n)
{
    int temp;
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (*(p + i) > *(p + j))
            {
                temp = *(p + i);
                *(p + i) = *(p + j);
                *(p + j) = temp;
            }
}

int Odd(int n)
{
    if (n % 2 == 0)
        return 0;// even
    else
        return 1; // odd
}

輸出爲: code

3----5----7----12----13----14----21----23----23----23----23----29----40----56----
中值爲: 22.000000io

相關文章
相關標籤/搜索