1、面试题

现在有一个数组arr1,它里面存储的字符串分别为@“zhangsan”@“lisi”@“wangwu”@“lisi”@“zhangsan”,请将它去重后赋值给可变数组arr2输出为:@“zhangsna”,@“lisi”,@“wangwu”。

解题思路:

1)创建一个可变字典

2)遍历这个数组将数组的字符串存储为这个字典的key和value

3)调用字典的一下任意一个方法

@property (readonly, copy) NSArray<KeyType> *allKeys;

@property (readonly, copy) NSArray<ObjectType> *allValues;

4)将获得的字符串存储在arr2中即可。

代码如下:

 NSArray *arr1 = @[@"zhangsan",@"lisi",@"wangwu",@"lisi",@"zhangsan"];

     NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString * str in arr1) {
[dict setObject:str forKey:str];
} NSMutableArray * arr2 = [NSMutableArray arrayWithObjects:[dict allKeys], nil]; NSLog(@"%@",arr2);

输出结果:

-- ::32.058 - nsarray[:] (
(
zhangsan,
lisi,
wangwu
)
)

原理:这个是根据字典的特性:key值唯一,当碰到俩个zhangsan时,他不会在创建一个键值对而是给上一个zhangsan的键值对再重新赋值

eg:

 NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithObjects:@[@"zhangsan",@"lisi"] forKeys:@[@"",@""]];

    NSLog(@"%@",dict);

输出结果:

2016-03-21 18:09:54.571 01- nsarray[1865:265560] {
1 = lisi;
}
05-13 23:23