数组中的最大值和次大值

    NSArray *arr = [NSArray arrayWithObjects:@(0.1),@(0.02),@(0.9),@(1.6),@(0.002),@(0.6), nil];
    float max = [arr[0] floatValue];
    int index = 0;
    float secondMax = [arr[1] floatValue];
    int secondIndex = 1;
    for (int i = 0; i < arr.count; i++) {
        if ([arr[i] floatValue] > max) {
            secondMax = max;
            secondIndex = index;
            max = [arr[i] floatValue];
            index = i;
        }else if( [arr[i] floatValue] < max && [arr[i] floatValue] > secondMax){
            secondMax = [arr[i] floatValue];
            secondIndex = i;
        }
    }

    NSLog(@"max %f index:%d secondMax:%f secondIndex:%d",max,index,secondMax,secondIndex);

 

max 1.600000 index:3 secondMax:0.900000 secondIndex:2

 

posted @ 2019-05-24 11:02  小师傅啊小师傅  阅读(407)  评论(0编辑  收藏  举报