我有很多这样的时间
[0.0、1.2、4.3、5.9、7.2、8.0]
播放音频文件时,我希望能够获取当前时间并查找数组中最近的较低数字。
我的方法是遍历数组,可能以相反的顺序遍历数组,因为感觉应该更快。有没有更好的办法?
回放应该是线性的,但可能是快进/倒带的,所以我想提出一个考虑到这一点的解决方案,但是我不确定如何解决这个问题。
最佳答案
您正在寻找的方法是-[NSArray indexOfObject:inSortedRange:options:usingComparator:]
。它执行二进制搜索。使用options:NSBinarySearchingInsertionIndex
选项,如果找不到确切的值,它将返回将插入对象的索引,该索引是最小的元素的索引或数组中的项数。
NSTimeInterval currentTime = ...;
NSUInteger index = [times indexOfObject:@(currentTime)
inSortedRange:NSMakeRange(0, times.count)
options:NSBinarySearchingInsertionIndex
usingComparator:^(id object0, id object1) {
NSTimeInterval time0 = [object0 doubleValue];
NSTimeInterval time1 = [object1 doubleValue];
if (time0 < time1) return NSOrderedAscending;
else if (time0 > time1) return NSOrderedDescending;
else return NSOrderedSame;
}];
// If currentTime was not found exactly, then index is the next larger element
// or array count..
if (index == times.count || [times[index] doubleValue] > currentTime) {
--index;
}
关于ios - 在排序的NSArray中找到最接近的较低数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23051912/