假設我有一個整數10.而我的NSMutableArray包含1到20個值。所以我必須從NSMutableArray中找到最大值10,意味着答案是11.將整數值與NSMutableArray進行比較,找到最大值
我知道如何找到最大值。
int max = [[numbers valueForKeyPath:@"@max.intValue"] intValue];
但我不知道如何比較並從數組中找到最大數目。我可以使用for循環來查找,但有沒有像上面的更快的解決方案?
假設我有一個整數10.而我的NSMutableArray包含1到20個值。所以我必須從NSMutableArray中找到最大值10,意味着答案是11.將整數值與NSMutableArray進行比較,找到最大值
我知道如何找到最大值。
int max = [[numbers valueForKeyPath:@"@max.intValue"] intValue];
但我不知道如何比較並從數組中找到最大數目。我可以使用for循環來查找,但有沒有像上面的更快的解決方案?
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;
假設你的數組是這樣的。
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;
}
}
這樣做。
我不想用循環.... –
試試這個:
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);
參考它希望它會幫助你.. http://stackoverflow.com/questions/25238072/find-the-largest-number-from-nsarray-那是小於給定數 –
意味着你想從數組中找到10個最大數? –
謝謝@PrashantTukadiya ..... –