-
Notifications
You must be signed in to change notification settings - Fork 199
/
SearchInsert.java
executable file
·60 lines (49 loc) · 1.46 KB
/
SearchInsert.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package Algorithms.divide2;
public class SearchInsert {
public int searchInsert1(int[] A, int target) {
if (A == null || A.length == 0) {
return 0;
}
int left = 0;
int right = A.length - 1;
while (left < right - 1) {
int mid = left + (right - left) / 2;
int num = A[mid];
if (num == target) {
return mid;
} else if (num < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
// bug 1: should use <=
if (target <= A[left]) {
return left;
// bug 2: should use <= . consider that may the result exit in left or right.
} else if (target <= A[right]) {
return right;
}
return right + 1;
}
// sol 2:
public int searchInsert(int[] A, int target) {
if (A == null || A.length == 0) {
return 0;
}
int left = 0;
int right = A.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int num = A[mid];
if (num == target) {
return mid;
} else if (num < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
}