← 返回 snapchat 的题目列表Search from the end in a sorted array (variant)
类型:online_judge
Problem
Given a non-decreasing sorted integer array nums (length n) and a target value target.
Find target starting from the end of the array and return the last index where target appears in nums. If target does not exist, return -1.
Note: “search from the end” means the result should be the last occurrence. You may implement it linearly or with binary search, but be ready to explain the complexity.
Follow-up
If there are many duplicates, how do you ensure you still return the last position? Can you achieve O(log n)?
I/O
Input: integer array nums, integer target
Output: integer, the last index of target (or -1 if not found)
Constraints
0 <= n <= 2 * 10^5
-10^9 <= nums[i], target <= 10^9
nums is sorted in non-decreasing order
Examples
nums = [1,2,2,2,3], target = 2 -> 3
nums = [1,1,1], target = 1 -> 2
nums = [1,2,3,4], target = 5 -> -1
nums = [], target = 1 -> -1
nums = [2,2,2,2], target = 2 -> 3
Example
Input
[1,2,2,2,3]
2
Output
3