力扣,https://leetcode.cn/problems/que-shi-de-shu-zi-lcof/description/
线性扫描,一般情况
class Solution {
public int takeAttendance(int[] records) {
boolean[] visited = new boolean[records.length + 1];
Arrays.fill(visited, false);
for (int i : records) {
visited[i] = true;
}
for (int i = 0; i < visited.length; ++i) {
if (!visited[i]) {
return i;
}
}
return -1;
}
}
二分搜索
class Solution {
public int takeAttendance(int[] records) {
return binarySearch(0, records.length - 1, records);
}
public int binarySearch(int left, int right, int[] records) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (records[mid] == mid) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;// 返回right + 1也可
}
}