Find duplicates in NSArray

≡放荡痞女 提交于 2019-12-07 06:45:08

问题


Say you have an NSArray with duplicates @[1,2,3,1,1,2,4,5,6];

Find all the duplicates; this can be in pseudocode. This is more of a algorithm question than a Foundation framework (without the use of NSSet) question.


回答1:


as @Lithu described, use NSCountedSet , see the below code.

NSArray *arr = [[NSArray alloc]initWithObjects:@(1),@(1),@(2), @(1),nil];
NSCountedSet *cs = [[NSCountedSet alloc] initWithArray:arr];
NSLog(@"object count greater than 1 are");
for(NSNumber *num in cs)
{
    if([cs countForObject:num]>1)
    NSLog(@"%@",num);
}



回答2:


Use an NSCountedSet and only print the elements that returns a number>1 for countForObject: method

Refer this for more information



来源:https://stackoverflow.com/questions/17691153/find-duplicates-in-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!