-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
searchInsertPosition.java
96 lines (85 loc) · 2.5 KB
/
searchInsertPosition.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
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
// Source : https://oj.leetcode.com/problems/search-insert-position/
// Inspired by : http://www.jiuzhang.com/solutions/search-insert-position/
// Author : Lei Cao
// Date : 2015-10-03
/**********************************************************************************
*
* 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
*
*
**********************************************************************************/
package searchInsertPosition;
public class searchInsertPosition {
public int searchInsert(int[] nums, int target) {
int i = searchInsertI(nums, target);
int j = searchInsertII(nums, target);
if (i == j) {
return i;
}
return -1;
}
// Find the first position >= target
private int searchInsertI(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
start = mid;
} else {
end = mid;
}
}
if (nums[start] >= target) {
return start;
}
if (nums[end] >= target) {
return end;
}
return end + 1;
}
// Find the last position < target, return + 1
// 1,2,3,5,6
private int searchInsertII(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
if (target < nums[0]) {
return 0;
}
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
start = mid;
} else {
end = mid;
}
}
if (nums[end] == target) {
return end;
} else if (nums[end] < target) {
return end + 1;
} else if (nums[start] == target) {
return start;
}
return start + 1;
}
}