findIndexByPosition static method
根据播放位置查找当前章节索引(二分查找,O(log n))
前提条件:chapters 必须按 startMs 升序排列,且章节区间连续不重叠。
如果传入未排序的列表,二分查找将返回错误结果。
Find chapter index by playback position using binary search (O(log n)).
Prerequisite: chapters must be sorted by startMs in ascending order,
and chapter intervals must be continuous and non-overlapping.
Passing an unsorted list will produce incorrect results.
chapters 章节列表
positionMs 当前播放位置(毫秒)
返回当前章节索引,未找到返回 -1
Implementation
static int findIndexByPosition(List<ChapterInfo>? chapters, int positionMs) {
if (chapters == null || chapters.isEmpty) return -1;
int low = 0;
int high = chapters.length - 1;
while (low <= high) {
final int mid = (low + high) >>> 1;
final ChapterInfo chapter = chapters[mid];
if (positionMs < chapter.startMs) {
high = mid - 1;
} else if (positionMs >= chapter.endMs) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
}