数组配对
问题:给定N个整数,N为偶数,是否能找到N/2对,似的每队和能被k整除。每个元素只能出现在一个配对中。
时间复杂度为O(n)的OC算法实现:
// // CheckPairable.h // Algorithm // // Created by han shuai on 2016/9/25. // Copyright © 2016年 han shuai. All rights reserved. // /** 9 */ #import <Foundation/Foundation.h> @interface CheckPairable : NSObject - (BOOL)checkPairable:(NSArray *)dataArr k:(int)k; @end
// // CheckPairable.m // Algorithm // // Created by han shuai on 2016/9/25. // Copyright © 2016年 han shuai. All rights reserved. // #import "CheckPairable.h" @implementation CheckPairable - (BOOL)checkPairable:(NSArray *)dataArr k:(int)k { if (k <= 0) { return false; } //counts[i] i为余数 counts[i] 为以i作为余数的个数 NSMutableArray *counts = [NSMutableArray array]; for (int i = 0; i<k; i++) { [counts addObject:@0]; } for (NSNumber *num in dataArr) { counts[[num intValue]%k] = [NSNumber numberWithInt:[counts[[num intValue]%k] intValue]+1]; } //整除k的个数若不是偶数 返回false if ([counts[0] intValue]%2 != 0) { return false; } //k是偶数时,查看余数k/2的个数是否为偶数 if (k % 2 == 0) { if ([counts[k/2] intValue] % 2 != 0) { return false; } } //余数配对 //余数为i 和 余数为 k-i 的个数是否相同 for (int i = 1; i <= k/2; i++) { if ([counts[i] intValue] != [counts[k-i] intValue]) { return false; } } return true; } @end
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。