Last Position of Target
lintcode
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.
思路
public class Solution {
public int lastPosition(int[] nums, int target) {
if (nums.length == 0) {
return -1;
}
int start = 0;
int end = nums.length - 1;
while (start < end - 1) {
int mid = start + (end - start) / 2;
if (nums[mid] > target) {
end = mid;
} else if (nums[mid] <= target) {
start = mid;
}
}
if (nums[end] == target) {
return end;
}
if (nums[start] == target) {
return start;
}
return -1;
}
}