forked from andavid/coding-interview-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMissingNumber.java
More file actions
32 lines (30 loc) · 941 Bytes
/
MissingNumber.java
File metadata and controls
32 lines (30 loc) · 941 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package _53;
public class MissingNumber {
/**
* 一个长度为n的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n之内。
* 在范围0~n内的n个数字有且只有一个数字不在该数组中,请找出。
*
* 用二分查找法找到数组中第一个数值不等于下标的数字。
*/
public static int getMissingNumber(int[] data) {
int low = 0;
int high = data.length - 1;
while (low <= high) {
int mid = low + (high - low)/2;
if (data[mid] == mid) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
public static void main(String[] args) {
int[] data1 = {0,1,2,3,4,5}; //6
int[] data2 = {0,1,3,4,5}; //2
int[] data3 = {1,2}; //0
System.out.println(getMissingNumber(data1));
System.out.println(getMissingNumber(data2));
System.out.println(getMissingNumber(data3));
}
}