Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

Find First and Last Position of Element in Sorted Array

class Solution {
    public int[] searchRange(int[] nums, int target){
        int[] ans = new int[2];
        ans[0] = searchElementIndex(nums, target, true);
        ans[1] = searchElementIndex(nums, target, false);
        return ans;
    }

    public int searchElementIndex(int[] nums, int target, boolean findFirstIndex){
        int index = -1;
        int start = 0;
        int end = nums.length-1;

        while (start <= end) {
            int mid = start + (end-start) / 2;

            if (findFirstIndex){
                if (nums[mid] >= target) end = mid-1;
                else start = mid+1;
            }else {
                if (nums[mid] <= target) start = mid+1;
                else end = mid-1;
            }
            if (nums[mid]==target) index = mid;
        }
        return index;
    }
}
 
PREVIOUS NEXT
Tagged: #Find #First #Last #Position #Element #Sorted #Array
ADD COMMENT
Topic
Name
9+4 =