Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathSearch Insert Position.java
More file actions
Latest commit
executable file
·106 lines (90 loc) · 2.47 KB
/
Copy pathSearch Insert Position.java
File metadata and controls
executable file
·106 lines (90 loc) · 2.47 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
E
一般的binarysearch.
在结尾判断该return哪个position。
```
/*
28% Accepted
Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
Tags Expand
Binary Search Array Sorted Array
*/
/*
Recap 12.08.2015
Find the occurance of the target, return it.
If not found, at the point, start + 1 = end
return the insert position at start + 1
*/
publicclassSolution {
publicintsearchInsert(int[] A, inttarget) {
if (A == null || A.length == 0) {//Insert at 0 position
return0;
}
intstart = 0;
intend = A.length - 1;
intmid = start + (end - start)/2;
while (start + 1 < end) {
mid = start + (end - start)/2;
if (A[mid] == target) {
returnmid;
} elseif (A[mid] > target) {
end = mid;
} else {
start = mid;
}
}
if (A[start] >= target) {
returnstart;
} elseif (A[start] < target && target <= A[end]) {
returnend;
} else {
returnend + 1;
}
}
}
//older version
publicclassSolution {
/**
* param A : an integer sorted array
* param target : an integer to be inserted
* return : an integer
*/
publicintsearchInsert(ArrayList<Integer> A, inttarget) {
// write your code here
intstart = 0;
intend = A.size() - 1;
intmid;
if (A == null || A.size() == 0 || target <= A.get(0)) {
return0;
}
//find the last number less than target
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (A.get(mid) == target) {//Since no duplicates, return when found
returnmid;
} elseif (A.get(mid) < target) {
start = mid;
} else {
end = mid;
}
}
//Always 2 elements left to check, first:start, second: end
if (A.get(end) == target) {
returnend;
}
if (A.get(end) < target) {
returnend + 1;
}
if (A.get(start) == target) {
returnstart;
}
returnstart + 1;
}
}
```