Find First and Last Position of Element in Sorted Array

LeetCode Q 34 - Find First and Last Position of Element in Sorted Array

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Solution

First we use binary search to find the target number, if it exists then we want to find the first and last index.
When finding these two indexes, we should also use binary search. Or our algorithm has a potential to become linear search when the data is like [1,1,1,1,1,1,1,2,3], then the time complexity would become O(n).

Code:

public int[] searchRange(int[] nums, int target) {
	if (nums == null || nums.length == 0)
		eturn new int[]{-1, -1};

	int[] res = new int[2];
	int left = 0, right = nums.length;
	int index = bs(nums, 0, nums.length - 1, target);
	if (index == -1)
		return new int[]{-1, -1};
	Arrays.fill(res, index);

    // find the left boundary
	left = index;
	while (left >= 0) {
		left = bs(nums, 0, left - 1, target);
		if (left == -1) break;
		else res[0] = left;
	}
	
	// find the right boundary
	right = index;
	while (right <= nums.length - 1) {
		right = bs(nums, right + 1, nums.length - 1, target);
		if (right == -1) break;
		else res[1] = right;
	}
    
	return res;
}

private int bs(int[] nums, int left, int right, int target) {
	while (left <= right) {
		int mid = (left + right) / 2;
		if (nums[mid] == target) return mid;
        else if (nums[mid] < target) left = mid + 1;
        else right = mid - 1;
	}
	return -1;
}

   Reprint policy


《Find First and Last Position of Element in Sorted Array》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC