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.
Assumptions
- There can be duplicate elements in the array.
Examples
- A = {1, 2, 3}, T = 2, return 1
- A = {1, 2, 3}, T = 4, return -1
- A = {1, 2, 2, 2, 3}, T = 2, return 1
Corner Cases
- What if A is null or A of zero length? We should return -1 in this case.
1 public int firstOccur(int[] array, int target) {
2 // Write your solution here
3 if(array == null || array.length == 0 ){
4 return -1 ;
5 }
6 int left = 0, right = array.length - 1 ;
7 //when left next to right then jump out
8 //note: first occurance, so if array[mid] == target, should move right, not left
9 while(left + 1 <right){
10 int mid = left + (right - left)/2;
11 if(array[mid] < target){
12 left = mid ;
13 } else{
14 right = mid ;
15 }
16 }
17 //post processing: since we need to handle left right not matching while
18 //first occurance, we check the left first
19 if(array[left] == target){
20 return left ;
21 }
22 if(array[right] == target){
23 return right ;
24 }
25 return -1;
26 }