Algorithm exercise: Array pairing

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.