在NSArray中查找重复项的索引 [英] Find indices of duplicates in a NSArray

查看:112
本文介绍了在NSArray中查找重复项的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,如

[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使用目标c .....

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≥.

推荐答案

您可以构建一个将对象映射到索引集的字典。对于每个索引集, -count 1 表示没有重复项,> 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);

这篇关于在NSArray中查找重复项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆