-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchRange.java
More file actions
101 lines (94 loc) · 2.49 KB
/
SearchRange.java
File metadata and controls
101 lines (94 loc) · 2.49 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
package searchRange;
public class SearchRange {
int[] tmp = {};
public int[] searchRange(int[] nums, int target) {
int[] result = new int[2];
this.tmp = nums;
int position = searchTarget(0, nums.length-1, target);
if(position == -1){
return new int[]{-1,-1};
}
else if(position == 0){
//search behind
result[0] = 0;
result[1] = searchBehind(position, target);
}
else if(position == nums.length-1){
//search forward
result[0] = searchFront(position, target);
result[1] = position;
}
else{
result[0] = searchFront(position, target);
result[1] = searchBehind(position, target);
}
return result;
}
public int searchTarget(int begin, int end, int target){
int position = (begin+end)/2;
if(end < begin){
return -1;
}
if(end - begin <= 1){
if(tmp[begin] == target){
return begin;
}
else if(tmp[end] == target){
return end;
}
else{
return -1;
}
}
if(tmp[position] == target){
return position;
}
else if(tmp[position] < target){
if(tmp[position+1] > target){
return -1;
}
return searchTarget(position + 1, end, target);
}
else {
if(tmp[position-1] < target){
return -1;
}
return searchTarget(begin, position-1, target);
}
}
public int searchFront(int position, int target){
int tmp_position = searchTarget(0, position-1, target);
int result = position;
while(tmp_position != -1){
if(tmp_position == 0){
return 0;
}
result = tmp_position;
position = tmp_position;
tmp_position = searchTarget(0, position-1, target);
}
return result;
}
public int searchBehind(int position, int target){
int last = this.tmp.length-1;
int temp_position = searchTarget(position +1, last, target);
int result = position;
while(temp_position != -1){
if(temp_position == last){
return last;
}
result = temp_position;
position = temp_position;
temp_position = searchTarget(position+1, last, target);
}
return result;
}
public static void main(String[] args){
SearchRange t = new SearchRange();
int[] nums = new int[]{5, 7, 7, 8, 8, 10};
int[] result = t.searchRange(nums, 8);
int position = t.searchTarget(0, nums.length-1, 8);
System.out.println("1="+result[0]+ " 2=" + result[1]);
System.out.println(position);
}
}