Last Position of Target
程序员文章站
2022-05-05 17:38:56
...
题目位置
https://www.lintcode.com/problem/last-position-of-target/description
题目描述
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
题目分析
给定一个升序的排序数组(数组中可能存在重复元素)和一个target,找target在数组中出现的最后一个位置。
注意
- 当nums[mid] == target的时候,需要将start = mid,因为如果把end = mid的话,万一mid之后还有等于target的元素,就无法找到它们了。
- 对于找last position的情况,在跳出循环之后做判断的时候,先判断end,再判断start。
参考代码
java版本
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) / 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;
}
}
python版本
class Solution:
"""
@param nums: An integer array sorted in ascending order
@param target: An integer
@return: An integer
"""
def lastPosition(self, nums, target):
# write your code here
if nums is None or len(nums) == 0:
return -1
start = 0
end = len(nums) - 1
while start + 1 < end:
mid = start + (end - start) // 2
if nums[mid] <= target:
start = mid
else:
end = mid
if nums[end] == target:
return end
if nums[start] == target:
return start
return -1
c++版本
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
/**
* @param nums: An integer array sorted in ascending order
* @param target: An integer
* @return: An integer
*/
int lastPosition(vector<int> &nums, int target) {
// write your code here
if (nums.empty()) {
return -1;
}
int start = 0;
int end = int(nums.size()) - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] <= target) {
start = mid;
} else {
end = mid;
}
}
if (nums[end] == target) {
return end;
}
if (nums[start] == target) {
return start;
}
return -1;
}
};
int main() {
Solution solution;
int a[6] = {1,2,2,4,5,5};
vector<int> nums(a, a + 6);
int target = 2;
cout << solution.lastPosition(nums, target);
return 0;
}
上一篇: Drying 二分查找
下一篇: 谈谈注解那些事
推荐阅读
-
coreldraw中如何精准控制对象 Position和Rotate按钮轻松搞定
-
在Spring中用select last_insert_id()时遇到问题
-
mysql中错误:1093-You can’t specify target table for update in FROM clause的解决方法
-
MySQL中的LOCATE和POSITION函数使用方法
-
html 之 position用法
-
IOS真机运行带有Notification Content target的时候证书报错This application or a bundle it contains has the same bun
-
Bootstrap中data-target 到底是什么
-
解决Hibernate JPA中insert插入数据后自动执行select last_insert_id()
-
iOS自定义UIBarButtonItem的target和action示例代码
-
使用CSS3的ruby-position固定注音位置的用法示例