查找 NSArray 中所有重复元素的索引

Find index of all duplicate elements in NSArray

很难解释为什么我需要数组中重复元素的索引。当我尝试以传统方式获取元素的索引时,它只显示一个索引,但我需要获取所有重复值的索引 例如:

NSArray *array=@[@"one",@"one",@"one",@"two",@"two",@"four",@"four",@"four"];
int index = [array indexOfObject:element];
NSLog(@"index %d",index);

这里,如果我尝试获取“one”的索引,它显示索引是 0,但我需要获取 one[= 的更多索引13=]

您可以像这样获取重复索引:

NSArray *array=@[@"one",@"one",@"one",@"two",@"two",@"four",@"four",@"four"];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
 {
     if ([obj isEqualToString:@"one"])
     {
         NSLog(@"index %d",idx);

     }
 }];
int i,count=0;
for (i = 0; i < [array count]; i++) {
    if element == [array objectAtIndex:i] {
        indices[count++] = i;
    }
}

声明一个空数组 indices,indices 将包含给定元素的所有索引。

NSString *element = @"one";
NSArray *array=@[@"one",@"one",@"one",@"two",@"two",@"four",@"four",@"four"];

NSIndexSet *matchingIndexes = [array indexesOfObjectsPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
    return [obj isEqual:element];
}];

[matchingIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
    NSLog(@"%ld", (long)idx);
}];

最终我认为 NSArray 方法不会在这里帮助您,因此您将不得不编写一些非常基本的代码。可能有一个更清晰的答案,但这里有一个相当简单的问题解决方案。

这只是遍历数组,并为每个唯一数字创建一个 NSDictionary。它假定数组按照您的示例进行排序,因此只需根据当前索引检查先前索引的值以查看它们是否已更改。当它们发生变化时,它知道该值已完成并将字典保存到数组中。

NSArray *array=@[@"one",@"one",@"one",@"two",@"two",@"four",@"four",@"four"];
NSString *priorString = array[0];
NSMutableDictionary *duplicatesByKey = [[NSMutableDictionary alloc] init];
NSMutableArray *indexesOfDuplicates = [[NSMutableArray alloc] init];

int index = 0;
for (NSString *string in array) {
    if ([priorString isEqualToString:string]) {
        [indexesOfDuplicates addObject:[NSNumber numberWithInt:index]];
    } else {
        [duplicatesByKey setObject:indexesOfDuplicates forKey:priorString];
        indexesOfDuplicates = [[NSMutableArray alloc] init];
        [indexesOfDuplicates addObject:[NSNumber numberWithInt:index]];
    }
    priorString = string;
    index ++;
}
[duplicatesByKey setObject:indexesOfDuplicates forKey:priorString];

希望对您有所帮助。

使用

NSCountedSet * countedSet = [NSCountedSet setWithArray: array];

NSSet * uncountedSet = [NSSet setWithArray: array];

-- 从你的数组和一个传统的 NSSet 创建一个计数集。

然后:

[countedSet minusSet: uncountedSet];

countedSet 现在将仅包含重复项(如果有)的元素,countForObject: 方法将 return 该元素的重复项数(超过 1 个)。