目标最后位置
题目:
描述
给一个升序数组,找到 target 最后一次出现的位置,如果没出现过返回 -1
样例
样例 1:
输入:nums = [1,2,2,4,5,5], target = 2
输出:2
样例 2:
输入:nums = [1,2,2,4,5,5], target = 6
输出:-1
public class Solution {
/**
* @param nums: An integer array sorted in ascending order
* @param target: An integer
* @return: An integer
*/
public int lastPosition(int[] nums, int target) {
// write your code here
int len = nums.length;
if(len == 0) {
return -1;
}
int l = 0, r = len - 1;
while(l <= r) {
int mid = l + (r - l) / 2;
int num = nums[mid];
if(num == target) {
l = mid + 1;
} else if(num < target) {
l = mid + 1;
} else {
r = mid - 1;
}
}
if(r < 0) {
return -1;
}
return nums[r] == target ? r : -1;
}
}
public class Solution {
/**
* @param nums: An integer array sorted in ascending order
* @param target: An integer
* @return: An integer
*/
public int lastPosition(int[] nums, int target) {
// write your code here
int len = nums.length;
if(len == 0) {
return -1;
}
int l = 0, r = len;
while(l < r) {
int mid = l + (r - l) / 2;
int num = nums[mid];
if(num == target) {
l = mid + 1;
} else if(num < target) {
l = mid + 1;
} else {
r = mid;
}
}
if(r == 0) {
return -1;
}
return nums[r - 1] == target ? r - 1 : -1;
}
}