算法笔记-哈希表之冰淇淋购买问题(Ice Cream Parlor)

问题描述:

sunny和johny两个人要到冰激凌店买冰淇淋。店里每次都有很多种口味,每种口味有自己的单价。他们俩一共带的钱总数为money。所有口味的单价组成一个列表是array。要求两个人必须将所带的钱消费完,买两种冰淇淋。假如每种冰淇淋在列表里从1开始标号,程序要打印出买的两种冰淇淋的标号

 Sample:

 ***** Input:
 ***** money = 4
 ***** cost = 1 4 5 3 2
 ***** Output:
 ***** 1 4


 ***** Input:
 ***** money = 4
 ***** cost = 2 2 4 3
 ***** Output:
 ***** 1 2

最直接的方法:双重for循环,时间复杂度为n平方

NSArray *array = @[@(1),@(4),@(5),@(3),@(2),@(9)];
NSInteger money = 10;

/// 时间复杂度 ——> n平方
for (int i = 0; i < array.count; i++) {
NSInteger value = money - [array[i] integerValue];
for (int j = i + 1; j < array.count; j++) {
if ([array[j] integerValue] == value) {
NSLog(@”—%d—-%d”,i+1, j+1);
break;
}
}
}

哈希表:Dictionary —> 一边构造哈希表一边遍历

/// 构建哈希表
NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
for (int i = 0; i < array.count ; i++) {
NSString *value = [array[i] description];
NSString *key = [NSString stringWithFormat:@”%ld”, money - value];
if ( [parameter.allKeys containsObject:key] && [parameter[key] integerValue] != i) {
NSLog(@”111—%d—–%ld”,i + 1, [parameter[key] integerValue] + 1);
return;
}
[parameter setValue:@(i) forKey:value];
}

运行结果

猜你喜欢

转载自blog.csdn.net/siyue_tian/article/details/81139539