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.
用二分法模板,缩范围时想一下怎么保证当前的数字不会被丢掉就好了。
其实就是因为这种要找最后一个第一个的题目才产生这种模板的。要最后一个所以逼着改指针不写= mid - 1写= mid,所以while条件不写start < end写start + 1 < end,所以最后要判断两个数而不是一个数。
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 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 if (nums[mid] == target){ start = mid; } else { end = mid; } } if (nums[end] == target){ return end; } if(nums[start] == target){ return start; } return -1; } }
时间: 2024-10-10 06:19:32