从 NSArray 中找到小于给定数字的最大数字 [英] Find the largest number from NSArray that is smaller than the given number
本文介绍了从 NSArray 中找到小于给定数字的最大数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个已排序的整数数组 int[],并且我想搜索与某个输入数字最接近的较小值.
Suppose I have a sorted array of integers int[], and I want to search the closest smaller value to some input number.
例如如果数组包含1
、23
、57
、59
、120
,输入为109
,输出应为59
.我已经尝试过这个,但它没有按需要工作.
for example if the array contains 1
, 23
, 57
, 59
, 120
and the input is 109
, the output should be 59
.
I have tried this but it is not working out as needed.
NSTimeInterval currentTime = self.player.currentTime;
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];
}];
推荐答案
您的代码与您提供的示例数据一起按预期工作:
Your code does work as expected with the example data you gave:
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);
输出:
Index: 4
检查您的输入.很可能它们不是您认为的那样.
Check your inputs. Likely they are not what you think they are.
这篇关于从 NSArray 中找到小于给定数字的最大数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文