-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirst Occurrence.java
More file actions
44 lines (40 loc) · 917 Bytes
/
First Occurrence.java
File metadata and controls
44 lines (40 loc) · 917 Bytes
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
/*
Given a target integer T and an integer array A sorted in ascending order,
find the index of the first occurrence of T in A or return -1 if there is no such index.
A = {1, 2, 3}, T = 4, return -1
A = {1, 2, 2, 2, 3}, T = 2, return 1
steps:
1 2 2 2 3
l m r
1 2 2 2 3
l m r
1 2 2 2 3
l r
check array[left] and array[right]
time = O(log(n))
space = O(1)
*/
public class Solution {
public int firstOccur(int[] array, int target) {
// Write your solution here
if (array == null || array.length == 0) {
return -1;
}
int left = 0;
int right = array.length - 1;
while (left + 1 < right) {
int mid = left + (right - left) / 2;
if (array[mid] >= target) {
right = mid;
} else {
left = mid;
}
}
if (array[left] == target) {
return left;
} else if (array[right] == target) {
return right;
}
return -1;
}
}