Find First and Last Position of Element in Sorted Array
LeetCode https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
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
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[] { -1, -1 };
if (nums == null || nums.length == 0) {
return res;
}
// Find the first occurrence
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
res[0] = mid;
right = mid - 1; // Continue searching on the left side
}
}
// Find the last occurrence
left = 0;
right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
res[1] = mid;
left = mid + 1; // Continue searching on the right side
}
}
return res;
}
}
Complexity
- Time = O(logn)
- Space = O(1)
This post is licensed under CC BY 4.0 by the author.