Method
search
(int nums[],int target, boolean isFirst)
Source from the content-addressed store, hash-verified
| 14 | } |
| 15 | |
| 16 | int search(int nums[],int target, boolean isFirst) |
| 17 | { |
| 18 | |
| 19 | // utility variables for binary search |
| 20 | int lo=0,hi=nums.length-1,mid=0; |
| 21 | int index=-1; |
| 22 | while(lo<=hi) |
| 23 | { |
| 24 | mid=lo+(hi-lo)/2; |
| 25 | |
| 26 | if(nums[mid]==target) |
| 27 | { |
| 28 | // for first |
| 29 | // if you see a number greater than or equal to target then move towards left |
| 30 | if(isFirst) |
| 31 | { |
| 32 | index=mid; |
| 33 | hi=mid-1; |
| 34 | } |
| 35 | // for second |
| 36 | // if you see a number less than or equal to target then move towards right |
| 37 | else |
| 38 | { |
| 39 | index=mid; |
| 40 | lo=mid+1; |
| 41 | } |
| 42 | } |
| 43 | else if(nums[mid]>target) hi=mid-1; |
| 44 | else lo=mid+1; |
| 45 | } |
| 46 | return index; |
| 47 | } |
| 48 | } |
Tested by
no test coverage detected