某班级 n 位同学的学号为 0 ~ n-1。点名结果记录于升序数组 records。假定仅有一位同学缺席,请返回他的学号。

示例 1:

**输入:**records = [0,1,2,3,5]
**输出:**4

示例 2:

**输入:**records = [0, 1, 2, 3, 4, 5, 6, 8]
**输出:**7

提示:

1 <= records.length <= 10000

二分查找,因为不缺席的话有 i=records[i],符合条件则说明缺席人员所在区间为右边

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int takeAttendance(vector<int> &records) {
int l = 0;
int r = records.size();
while (l < r) {
int mid = l + (r - l) / 2;
if (mid == records[mid])
l = mid + 1;
else if (mid < records[mid])
r = mid;
}
return l;
}
};