混合兩個有序int數組到另一個有序數組並去重

來源:互聯網
上載者:User

標籤:

題目:兩個有序數組a和b,混合之,放在另一個數組c中,使得c也是有序數組(升序),去除重複的項。

雖然覺得不是很簡便,但代碼如下:

int merge_array (int *a , int *b, int *c, int n1, int n2){    if (n1 < 0 || n2 < 0) {        return -1;    }    int i = 0;    int j = 0;    int k = 0;    int count = 0;    while (i < n1 && j < n2) {        if (a[i] < b[j]) {            if (k == 0) {                c[k++] = a[i++];                count++;            }else{                if (c[k-1] != a[i]) {                    c[k++] = a[i++];                    count++;                }else{                    i++;                }            }        }else if (a[i] == b[j]){            if (k == 0) {                c[k++] = a[i++];                j++;                count++;            }else{                if (c[k-1] != a[i]) {                    c[k++] = a[i++];                    j++;                    count++;                }else{                    i++;                    j++;                }            }        }else{            if (k == 0) {                c[k++] = b[j++];                count++;            }else{                if (c[k-1] != b[j]) {                    c[k++] = b[j++];                    count++;                }else{                    j++;                }            }        }    }    while (i < n1) {        if (k == 0) {            c[k++] = a[i++];            count++;        }else{            if (c[k-1] != a[i]) {                c[k++] = a[i++];                count++;            }else{                i++;            }        }    }    while (j < n2) {        if (k == 0) {            c[k++] = b[j++];            count++;        }else{            if (c[k-1] != b[j]) {                c[k++] = b[j++];                count++;            }else{                j++;            }        }    }    return count;}

測試代碼如下:

int a[1] = {1};        int b[1] = {2};        int c[100] = {0};        int count = merge_array(a, b, c, 1, 01);        for (int i = 0; i < count; i++) {            printf("c[%d] : %d\n", i, c[i]);        }

測試多次,包括各種重複項、0項、負數項,運行都是正確的,歡迎大家提出更好的方法!

晚安。

混合兩個有序int數組到另一個有序數組並去重

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.