Find indices of duplicates in a NSArray

为君一笑 提交于 2019-12-10 11:49:27

问题


i have an array like

[chapter,indent,left,indent,nonindent,chapter,chapter,indent,indent,left];

i need to find indexes of duplicates and also non duplicate elements . how to do this...........give some sample code or logic...... thanks in advance

iam using objective c.....

    NSArray *myWords = [string componentsSeparatedByString:@"class=\""];

    int count_var=[myWords count];


    tmp1=@"";
    for(int i=1;i<count_var;i++)
    {

        str=[NSString stringWithFormat:@"\n%@",[myWords objectAtIndex:i]];
        class=[str componentsSeparatedByString:@"\""];

        NSString *tmp=[NSString stringWithFormat:@"%@",[class objectAtIndex:0]];
        tmp1=[[NSString stringWithFormat:@"%@",tmp1] stringByAppendingString:[NSString stringWithFormat:@"%@",tmp]];
    } 
    t1.editable=NO;
    t1.text=tmp1;
NSArray *tempo=[[NSArray alloc]init];
tempo=[tmp1 componentsSeparatedByString:@"\n"];

tempCount=[tempo count];

this is my sample code...in this the array tempo contains all objects from that array i want to get index of duplicate strings≥.


回答1:


You could build a dictionary mapping the objects to index sets. For every index set, a -count of 1 means no duplicates, > 1 means there are duplicates.

NSArray *arr = [NSArray arrayWithObjects:...];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];

for (NSUInteger i=0; i<[arr count]; ++i) {
    id obj = [arr objectAtIndex:i];
    NSMutableIndexSet *ids = [dict objectForKey:obj];
    if (!ids) {
        ids = [NSMutableIndexSet indexSet];
        [dict setObject:ids forKey:obj];
    }
    [ids addIndex:i];
}

NSLog(@"%@", dict);


来源:https://stackoverflow.com/questions/3757540/find-indices-of-duplicates-in-a-nsarray

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