ios - 在排序的NSArray中找到最接近的较低数字

标签 ios objective-c arrays

我有很多这样的时间
[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/

相关文章:

javascript - 将数组中的数据连接到对象以通过中间人转换其值

javascript - 将函数作为参数传递给 array.prototype.filter

ios - 如何在 native iOS Facebook 应用程序中使用其应用程序范围 ID 打开某人的个人资料页面

ios - 在 Swift 3 中将结构写入 outputStream

ios - 检查是否允许本地通知

objective-c - 显示删除按钮时调整 UITableViewCell 内容的大小

c++ - vector c++ 的奇怪行为

iOS 嵌套 UITableView 不必要地加载所有单元格

html - Mathjax 的 iOS Swift 语法

objective-c - textDidChange 与 controlTextDidChange