編程演算法 - 兩個升序列的相同元素 代碼(C)

來源:互聯網
上載者:User

標籤:mystra   編程演算法   兩個升序列的相同元素   指標   代碼   

兩個升序列的相同元素 代碼(C)


本文地址: http://blog.csdn.net/caroline_wendy


兩個升序列的相同元素, 需要使用兩個指標, 依次遍曆, 如果相等輸出, 如果小於或大於, 則增加一個指標.

直到輸出所有的值.


代碼:

/* * main.cpp * *  Created on: 2014.9.19 *      Author: spike */#include <stdio.h>int Common(int data1[], int length1, int data2[], int length2, int res[]) {if (data1 == NULL || length1 <= 0 || data2 == NULL || length2 <= 0)return -1;int i=0, j=0, k=0;while (i < length1 && j < length2) {if (data1[i] == data2[j]) {res[k++] = data1[i];i++;j++;}else if (data1[i] < data2[j])i++;elsej++;}return k;}int main(void){int data1[] = {1, 2, 4, 5, 6, 9, 11};int data2[] = {2, 5, 6, 8, 12};int length1 = sizeof(data1)/sizeof(data1[0]);int length2 = sizeof(data2)/sizeof(data2[0]);int max = length1 > length2 ? length1 : length2;int* res = new int[max];int num = Common(data1, length1, data2, length2, res);for (int i=0; i<num; ++i) {printf("%d ", res[i]);}printf("\n");    return 0;}

輸出:

2 5 6 





編程演算法 - 兩個升序列的相同元素 代碼(C)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.