Last Position of Target

Find the last position of a target number in a sorted array. Return -1 if target does not exist.

Example:

Given [1, 2, 2, 4, 5, 5].

For target = 2, return 2.

For target = 5, return 5.

For target = 6, return -1.

Solution:

This is an extension of First Position of Target. To find the last duplicate, when nums[mid] == target, assign mid to start. This will drop all elements which before mid. The last element is kept either in nums[mid] or nums[start], when there are only two elements left. But remember, we have to check nums[end] before nums[start] this time.

Code:

public int lastPosition(int nums[], int target) {
    if (nums == null || nums.length == 0) {
        return -1;
    }
    int start = 0;
    int end = nums.length - 1;
    while (start + 1 < end) {
        int mid = start + (end - start) / 2;
        if (nums[mid] <= target) {
            start = mid;
        } else {
            end = mid;
        }
    }
    if (nums[end] == target) {
        return end;
    }
    if (nums[start] == target) {
        return start;
    }
    return -1;
}

results matching ""

    No results matching ""