美文网首页
在一个数组中 找和给定数的下标

在一个数组中 找和给定数的下标

作者: _Waiting_ | 来源:发表于2020-05-20 11:44 被阅读0次
     - (void)viewDidLoad {
        [super viewDidLoad];
        NSArray *arr = @[@"1",@"3",@"5",@"7",@"11"];
        
        NSArray *indexArr = [self getIndexWithSum:12 InArr:arr];
        
        if (indexArr.count>0) {
            NSLog(@"-->%@",indexArr);
        }else{
            NSLog(@"数组中没有要找的数据");
        }
        
    }
    
    
    -(NSArray *)getIndexWithSum:(NSInteger )sum InArr:(NSArray *)arr{
        
        NSMutableArray *indexArr = [NSMutableArray array];
        NSMutableDictionary *indexDic = [NSMutableDictionary dictionary];
        
        for (int i = 0 ; i < arr.count; i++) {
            
            NSInteger otherNum = sum - [arr[i] integerValue];
            
            if ([[indexDic allKeys] containsObject:arr[i]]) {
                NSLog(@"before index--->%@",[indexDic objectForKey:arr[i]]);
                NSLog(@"after index --->%d",i);
                [indexArr addObject:[indexDic objectForKey:arr[i]]];
                [indexArr addObject:@(i)];
                break;
            }else{
                [indexDic setValue:[NSString stringWithFormat:@"%d",i] forKey:[NSString stringWithFormat:@"%ld",otherNum]];
            }
            
            
        }
        
        
        return indexArr;
    }
    

    相关文章

      网友评论

          本文标题:在一个数组中 找和给定数的下标

          本文链接:https://www.haomeiwen.com/subject/wrpgohtx.html