Find the last position of a target
number in a sorted array. Return -1
if target does not exist.
Example
Example 1:
Input: nums = [1,2,2,4,5,5], target = 2
Output: 2
Example 2:
Input: nums = [1,2,2,4,5,5], target = 6
Output: -1
思路1:用recursion写,自己写出来的,开心。
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) {
if(nums == null || nums.length == 0) return -1;
int start = 0; int end = nums.length-1;
return findLastIndex(nums, start, end, target);
}
public int findLastIndex(int[] nums, int start, int end, int target) {
if(start > end) {
return -1;
}
int mid = start +(end-start) / 2;
if(nums[mid] == target){
if(mid == nums.length-1) return mid;
if(nums[mid] != nums[mid+1]){
return mid;
}
return findLastIndex(nums, mid+1, end, target);
} else if(nums[mid] < target) {
return findLastIndex(nums, mid+1, end, target);
} else { // nums[mid] > target;
return findLastIndex(nums, start, mid-1, target);
}
}
}
思路2: 用while循环写,按照九章的模板来写。
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) {
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 {
// nums[mid] > target;
end = mid;
}
}
if(nums[end] == target){
return end;
}
if(nums[start] == target){
return start;
}
return -1;
}
}