【发布时间】:2014-01-13 10:44:04
【问题描述】:
我有一个充满 PhRecords 的数组。为简单起见,让我们考虑对象的结构如下:
@interface PhRecord : NSObject
@property (nonatomic, strong) NSArray *PhName; //Person's name
@property (nonatomic, strong) NSArray *PhNumbers; //Person will have 2/3 contact numbers
@property (nonatomic, strong) NSArray *PhTypes; //The types of the contact numbers
@end
我的班级有一个属性,它通过电话簿并以上面指定的格式将姓名和电话号码收集到一个数组中。假设数组如下
@property (nonatomic, strong) NSArray *allContacts;
另外,我可以通过以下方法将所有联系人作为 PhRecords 获取
- (NSArray *)getAllContacts;
我有一个方法,如果我提供联系电话,它会找到联系人的姓名和类型。
//Assume that both string1 and string2 don't have (,),*,#,+ and "<white space>"
- (void)findContactByPhoneNumber:(NSString *)phNum {
NSString *string1 = phNum;
NSArray *contacts = [self getAllContacts];
for(SDPhoneRecord *record in contacts) {
for(int j=0;j<record.PhNumbers.count;j++) {
NSString *string2 = [[record.PhNumbers objectAtIndex:j];
if([string2 rangeOfString:string1].location!=NSNotFound) {
NSLog(@"Name:%@,Type:%@",record.PhName,[record.PhTypes objectAtIndex:j];
}
}
}
}
如您所见,此搜索的时间复杂度为 O(n^2)。是否可以进行 O(1) 查找?如果我必须使用谓词,我该如何使用它们来满足这种要求,其中字符串的“范围”必须与字符串传递的参数进行比较?
【问题讨论】:
-
有可能接近 O(n)。您需要做的就是为您的 PhNumbers 对象使用 NSDictionary 或其他有效搜索的对象。
-
好的,我会相应地修改数据结构。非常感谢您的建议!
标签: objective-c arrays search