- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathSearchInsertPosition35.java
More file actions
Latest commit
60 lines (52 loc) · 1.48 KB
/
Copy pathSearchInsertPosition35.java
File metadata and controls
60 lines (52 loc) · 1.48 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
/**
* 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.
*
* Here are few examples.
* [1,3,5,6], 5 → 2
* [1,3,5,6], 2 → 1
* [1,3,5,6], 7 → 4
* [1,3,5,6], 0 → 0
*/
publicclassSearchInsertPosition35 {
publicintsearchInsert(int[] nums, inttarget) {
for (inti = 0; i < nums.length; i++) {
if (nums[i] >= target) {
returni;
}
}
returnnums.length;
}
/**
* https://discuss.leetcode.com/topic/7874/my-8-line-java-solution
*/
publicintsearchInsert2(int[] A, inttarget) {
intlow = 0, high = A.length-1;
while(low <= high){
intmid = (low + high) / 2;
if(A[mid] == target) returnmid;
elseif(A[mid] > target) high = mid-1;
elselow = mid+1;
}
returnlow;
}
publicintsearchInsert3(int[] nums, inttarget) {
if (nums.length == 0) return0;
if (target > nums[nums.length-1]) returnnums.length;
intl = 0;
intr = nums.length-1;
while (l < r) {
intmid = (r - l) / 2 + l;
if (nums[mid] == target) returnmid;
elseif (nums[mid] < target) {
l = mid + 1;
} else {
r = mid;
}
}
returnl;
}
}