First, the problem description
Given n integers,n is even, can we find n/2 pairs, so that each pair and can be divisible by K . Note: Each element can only appear in one pairing.
Second, observation, analysis
The result can be judged by the remainder of each number being divisible by K . See the following code for a specific procedure.
Third, the realization of programming
Array pairing # include <iostream>using namespace Std;bool checkpairable (int narray[], int ncount, int k) {int* pcounts = new Int[k];memset (pcounts, 0, sizeof (int) *k);//save remainder 0,1,3,..., k-2,k-1 number for (int i = 0; i < ncount; ++i) {pcounts[narray[i]%k]++;} Determine if the number divisible by K is even if (Pcounts[0]% 2! = 0) {return false;} If k is even, determine if the remainder is K/2 is even if (k% 2 = = 0 && PCOUNTS[K/2]% 2! = 0) {return false;} Determine if the remainder is the same as the number of k-i for (int i = 1; I <= k/2; ++i) {if (pcounts[i]! = Pcounts[k/2-i]) {return false;}} if (null! = pcounts) {Delete pcounts;pcounts = NULL;} return true;} int main () {int narray[] = {1, 3, 5, 8, 8, 9, ten, 2};cout << checkpairable (NArray, _countof (NArray), 2) << Endl;return 0;}
Series Article Description:
1. This series of articles [algorithmic exercises] is just a record of my learning process and self-motivated, and there is no didactic meaning. It is my pleasure to bring a little knowledge and sentiment to the reader.
2. This series of articles is I learn contacts teacher "into Silicon Valley, programmer interview Secret" a book and write some experience, the majority of the article views from this book, hereby explain!
3. In the article, there are inevitably many errors and shortcomings, welcome readers to criticize, thank you.
Hill son
Reprint Please indicate the source, thank you. Original address:http://blog.csdn.net/s634772208/article/details/46493087
Algorithm exercise: Array pairing