leetbook_ioa/docs/LCR 173. 点名.md
排序数组中的搜索问题,首先想到 二分法 解决。根据题意,数组可以按照以下规则划分为两部分。
缺失的数字等于 “右子数组的首位元素” 对应的索引;因此考虑使用二分法查找 “右子数组的首位元素” 。
下图中的
nums对应本题的records。
{:align=center width=500}
<,,,,,>
class Solution:
def takeAttendance(self, records: List[int]) -> int:
i, j = 0, len(records) - 1
while i <= j:
m = (i + j) // 2
if records[m] == m: i = m + 1
else: j = m - 1
return i
class Solution {
public int takeAttendance(int[] records) {
int i = 0, j = records.length - 1;
while(i <= j) {
int m = (i + j) / 2;
if(records[m] == m) i = m + 1;
else j = m - 1;
}
return i;
}
}
class Solution {
public:
int takeAttendance(vector<int>& records) {
int i = 0, j = records.size() - 1;
while(i <= j) {
int m = (i + j) / 2;
if(records[m] == m) i = m + 1;
else j = m - 1;
}
return i;
}
};