1. 程式人生 > >尋找最小的K個數

尋找最小的K個數

舉一反三:

#include <iostream>
#define N 5
#define K 5
using namespace std;

void SearchLatestK();

int arrA[] = {2,5,8,10,11};
int arrB[] = {1,3,5,7,9};
int arrC[K];

int main(int argc, char const *argv[])
{

	SearchLatestK();
	for(int i = 0; i < K; i++)
		cout<<arrC[i]<<" ";
	return 0
; } void SearchLatestK(){ int count = 1; int i = 0, j = 1, compi = 1, compj = 0; arrC[0] = arrA[0] + arrB[0]; while(count < K){ if((arrA[i] + arrB[j]) < (arrA[compi] + arrB[compj])){ arrC[count++] = arrA[i] + arrB[j];//兩陣列首元素相加肯定最小。 j = ++j == N ? 0,i = compi+1 : j;//這樣的語法也可以,初嘗試。 } else
{ arrC[count++] = arrA[compi] + arrB[compj]; compj = ++compj == N ? 0,compi = i + 1 : compj; } if (i == N ){//當其中一個數組走到了盡頭,說明只剩下最後一組和了 while(count < K) arrC[count++] = arrB[compj]; return; } else if( compi == N){ while(count < K) arrC[count++] = arrB[j]; return; } } }