Skip to content

Commit 354044a

Browse files
authored
Add java solution for 34 (qiyuangong#65)
* Add 034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java Contributed by @BHwi
1 parent b11d3c9 commit 354044a

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Solution {
2+
/*
3+
Rule 1
4+
- Given array is sorted in non-decreasing order
5+
6+
Rule 2
7+
- Limit time complexity O(log n).
8+
9+
So I can use Binary Search Algorithm.
10+
*/
11+
public int[] searchRange(int[] nums, int target) {
12+
// initialize arr[0] -> maximum integer, arr[1] -> minimum integer
13+
int[] arr = {100001, -10};
14+
int s = 0;
15+
int e = nums.length - 1;
16+
17+
// find minimum index in nums with Binary Search alogorithm
18+
while (s <= e) {
19+
20+
int mid = (s + e) / 2;
21+
22+
if(nums[mid] > target) {
23+
e = mid - 1;
24+
}
25+
else if(nums[mid] <= target) {
26+
if(nums[mid] == target) {
27+
arr[0] = Math.min(arr[0], mid);
28+
arr[1] = Math.max(arr[1], mid);
29+
}
30+
s = mid + 1;
31+
}
32+
}
33+
34+
s = 0;
35+
e = nums.length - 1;
36+
37+
// find maximum index in nums with Binary Search alogorithm
38+
while(s <= e) {
39+
int mid = (s + e) / 2;
40+
41+
if(nums[mid] >= target) {
42+
if(nums[mid] == target) {
43+
arr[0] = Math.min(arr[0], mid);
44+
arr[1] = Math.max(arr[1], mid);
45+
}
46+
e = mid - 1;
47+
}
48+
else if(nums[mid] < target) {
49+
s = mid + 1;
50+
}
51+
}
52+
53+
// if arr data is initial data, set -1.
54+
if(arr[0] == 100001) arr[0] = -1;
55+
if(arr[1] == -10) arr[1] = -1;
56+
57+
return arr;
58+
}
59+
}

0 commit comments

Comments
 (0)