设为首页 加入收藏

TOP

找出最小元素A与B的联盟(一)
2013-05-14 09:22:50 来源: 作者: 【 】 浏览:410
Tags:找出 最小 元素 联盟

    Give you two sorted array, find the k-th smallest elements of union of A and B, you can assume that there are no duplicate elements. the size of A is m, and size of B is n, both them are in acsending order.
    At first, we can use brute-force,  malloc a new array of size m+n, and merge A and B into this new array, then we can get the k-th smallest element, or k-th smallest elements. time complexity is O(m+n), and the space complexity is O(m+n);
    A better way, using two pointers: i, and j, i proints head of A, j points to head of B, at the same time make a new malloc of array of size k. then we compare A[i] and B[j], we get the minimum of them and increase pointer of the minimum one in order to get next index of the array its belonged to. time complexity is O(k), and space complexity is O(k)。 here is the codes:
    [cpp]
    #include<iostream>
    #include<cassert>
    using namespace std;
    int *get_k_th_minimum(int *a, int len_a, int *b, int len_b, int k) {
    int p = 0;
    int i = 0;
    int j = 0;
    int *c = (int*)malloc(sizeof(int) * k);
    if(a == NULL || b == NULL || k > (len_a + len_b)) {
    return NULL;
    }
    while(p < k && i < len_a && j < len_b) {
    if(a[i] < b[j]) {
    c[p++] = a[i];
    i++;
    } else {
    c[p++] = b[j];
    j++;
    }
    }
    return c;
    }
    void main() {
    int a[] = {1, 3, 5, 7, 9};
    int b[] = {2, 4, 6, 8, 10};
    int len_a = sizeof(a) / sizeof(int);
    int len_b = sizeof(b) / sizeof(int);
    int k = 5;
    int *p = get_k_th_minimum(a, len_a, b, len_b, k);
    int i = 0;
    if(p) {
    for(i = 0; i < k; i++) {
    cout 《 p[i] 《 " ";
    }
    cout 《 endl;
    }
    getchar();
    }
    Then a more better way, it takes O(lgm + lgn) time to get the k-th minimum elements, not all the number of k elements. then we will take O(k) time to get these elements from A and B. And space complexity is O(1)。

   

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++中动态资源管理 下一篇使用TCP协议实现文件传输

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: