8000 Sync LeetCode submission - Find First and Last Position of Element in… · thatbeautifuldream/leetcode-sync@172117f · GitHub
[go: up one dir, main page]

Skip to content

Commit 172117f

Browse files
Sync LeetCode submission - Find First and Last Position of Element in Sorted Array (java)
1 parent bc7b366 commit 172117f

File tree

1 file changed

+40
-0
lines changed
  • practice/problems/find_first_and_last_position_of_element_in_sorted_array

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public int[] searchRange(int[] nums, int target) {
3+
int[] ans = {-1,-1};
4+
int start = 0;
5+
int end = nums.length - 1;
6+
//to find first index
7+
while(start <= end) {
8+
int mid = start + (end - start)/2;
9+
if(nums[mid] == target) {
10+
ans[0] = mid;
11+
//continue searching left
12+
end = mid - 1;
13+
}
14+
else if(nums[mid] > target) {
15+
end = mid - 1;
16+
}
17+
else {
18+
start = mid + 1;
19+
}
20+
}
21+
//to find last index
22+
start = 0;
23+
end = nums.length - 1;
24+
while(start <= end) {
25+
int mid = start + (end - start)/2;
26+
if(nums[mid] == target) {
27+
ans[1] = mid;
28+
//continue searching right
29+
start = mid + 1;
30+
}
31+
else if(nums[mid] > target) {
32+
end = mid - 1;
33+
}
34+
else {
35+
start = mid + 1;
36+
}
37+
}
38+
return ans;
39+
}
40+
}

0 commit comments

Comments
 (0)
0