题解 | #缺失数字#
缺失数字
http://www.nowcoder.com/practice/9ce534c8132b4e189fd3130519420cde
二分:
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 找缺失数字 * @param a int整型vector 给定的数字串 * @return int整型 */ int solve(vector<int>& a) { // write code here int length = a.size(); int left = 0; int right = length - 1; int mid; // 特例: // [0,1,2,3,4,5,6,7,8] 输出 9 if (right == a[right]) return length; while (left <= right) { mid = left + (right - left) / 2; if (a[mid] == mid) { left = mid + 1; } else if (a[mid] > mid) { right = mid - 1; } } return a[left] - 1; } };