LeetCode 34. Find First and Last Position of Element in Sorted Array
作者:互联网
LeetCode 34. Find First and Last Position of Element in Sorted Array ()
题目
链接
https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
问题描述
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:
你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
示例
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
提示
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums 是一个非递减数组
-109 <= target <= 109
思路
同样是基础的二分查找,我们需要注意的就是,这个既要求左边界又要求右边界,为了避免出现错误,我用了两段分别求左右,然后判断是否符合条件。
复杂度分析
时间复杂度 O(logn)
空间复杂度 O(1)
代码
Java
public int[] searchRange(int[] nums, int target) {
int[] ans = new int[2];
int left1 = 0, left2 = 0;
int right1 = nums.length - 1, right2 = nums.length - 1;
while (left1 <= right1) {
int mid = left1 + (right1 - left1) / 2;
if (nums[mid] < target) {
left1 = mid + 1;
} else if (nums[mid] > target) {
right1 = mid - 1;
} else if (nums[mid] == target) {
right1 = mid - 1;
}
}
ans[0] = left1;
while (left2 <= right2) {
int mid = left2 + (right2 - left2) / 2;
if (nums[mid] < target) {
left2 = mid + 1;
} else if (nums[mid] > target) {
right2 = mid - 1;
} else if (nums[mid] == target) {
left2 = mid + 1;
}
}
ans[1] = right2;
if (left1 >= nums.length || nums[left1] != target || right2 < 0 || nums[right2] != target) {
ans[0] = -1;
ans[1] = -1;
return ans;
}
return ans;
}
标签:Last,target,nums,int,mid,Element,ans,LeetCode,left1 来源: https://www.cnblogs.com/blogxjc/p/15989363.html