题目:
一个长度为n-1的递增排序数组中所有的数字都是唯一的,并且每个数字的都在0-n-1之内。请在范围0-n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。
解答:
1 public class Solution { 2 3 public static int getMissingNumber(int[] arr, int length) { 4 if(arr == null || length <= 0) { 5 return -1; 6 } 7 8 int left = 0; 9 int right = length-1; 10 11 while(left <= right) { 12 int mid = (right+left)>>1; 13 if(arr[mid] != mid) { 14 if(mid == 0 || arr[mid-1] == mid-1) { 15 return mid 16 } 17 18 right = mid - 1; 19 } else { 20 left = mid + 1; 21 } 22 } 23 24 if(left == length) { 25 return length; 26 } 27 28 return -1; 29 } 30 }