Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

Find First and Last Position of Element in Sorted Array

class Solution {
    public int[] searchRange(int[] array, int target){
      int[] index = {-1, -1};
      int start = 0;
      int end = array.length-1;
      while (start <= end) {
          int mid = start + (end - start) / 2;
          if (array[mid] >= target) end = mid - 1;
          else start = mid + 1;
          if (array[mid] == target) index[0] = mid;
      }

      // resetting the start and end
      start = 0;
      end = array.length-1;
      while (start <= end){
          int mid = start  + (end-start) / 2;
          if (array[mid] <= target) start = mid+1;
          else end = mid-1;
          if (array[mid] == target) index[1] = mid;
      }
      return index;
    }
}
 
PREVIOUS NEXT
Tagged: #Find #First #Last #Position #Element #Sorted #Array
ADD COMMENT
Topic
Name
8+6 =