将整数值与NSMutableArray进行比较,并找到该值的最大值

时间:2015-09-26 05:48:33

标签: ios objective-c iphone ipad

假设我有一个整数10.我的NSMutableArray包含1到20个值。所以我必须从NSMutableArray中找到最多10个,这意味着答案是11。

我知道如何找到最大数量。

int max = [[numbers valueForKeyPath:@"@max.intValue"] intValue];

但我不知道如何比较并从数组中找到最大数量。我可以使用for循环来查找,但有没有像上面那样更快的解决方案?

3 个答案:

答案 0 :(得分:3)

NSArray *_timesArray = @[@1, @23, @57, @59, @120];
NSTimeInterval currentTime = 109;
NSInteger playerTime=currentTime;
NSUInteger index = [_timesArray indexOfObject:@(playerTime)
                                inSortedRange:NSMakeRange(0, _timesArray.count-1)
                                      options:NSBinarySearchingFirstEqual | NSBinarySearchingInsertionIndex
                              usingComparator:^(id a, id b) {
                                  return [a compare:b];
                              }];
NSLog(@"Index: %lu", (unsigned long)index);

你的答案是4;

答案 1 :(得分:2)

假设你的数组是这样的。

NSMutableArray *numbers = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20", nil];

并宣布你的电话号码。

int max = 11;
int find;

这里max是你的静态声明。并找到你的结果最大数字。

for(int i = 0;i<numbers.count;i++)
{
     if(max < [[numbers objectAtIndex:i]intValue])
     {
         find = [[numbers objectAtIndex:i]intValue];
         NSLog(@"%d",find);
         break;
     }
}

这样做。

答案 2 :(得分:0)

试试这个:

NSMutableArray *numbers = [[NSMutableArray alloc] initWithObjects:@"20", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10", @"11", @"12", @"13", @"14", @"15", @"16", @"17", @"18", @"19", @"20", nil];
    int minimum = 10;
    int nextNumber = [[numbers valueForKeyPath:@"@max.intValue"] intValue];

    for(int i = 0;i<numbers.count;i++)
    {
        if([[numbers objectAtIndex:i] intValue] > minimum) {
            if([[numbers objectAtIndex:i] intValue] < nextNumber) {
                nextNumber = [[numbers objectAtIndex:i] intValue];
            }
        }
    }

    NSLog(@"Maxmimum number right after %d from whole array is: %d",minimum, nextNumber);