【LeetCode】#34在排序数组中查找元素的第一个和最后一个位置(Find First and Last Position of Element in Sorted Array)
题目描述
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]。
示例
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]
Description
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Example
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
解法
class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums.length==0){
return new int[]{-1,-1};
}
int len=nums.length, l=0, m=len/2, r=len-1;
int num1 = -1;
while(true){
int left=nums[l], mid=nums[m], right=nums[r];
if(left==target){
num1 = l;
break;
}
if(mid==target){
num1 = m;
break;
}
if(right==target){
num1 = r;
break;
}
if(Math.abs(m-r)<=1 && Math.abs(m-l)<=1){
return new int[]{-1,-1};
}
if(left<mid){
if(left<target && target<mid){
r = m;
m = (l+r)/2;
continue;
}else{
l = m;
m = (l+r)/2;
continue;
}
}
if(mid<right){
if(mid<target && target<right){
l = m;
m = (l+r)/2;
continue;
}else{
r = m;
m = (l+r)/2;
continue;
}
}
}
int num2 = num1;
while(true){
if(nums[num1]==target){
num1--;
}else{
num1++;
break;
}
if(num1<0){
num1 = 0;
break;
}
}
while(true){
if(nums[num2]==target){
num2++;
}else{
num2--;
break;
}
if(num2>len-1){
num2 = len-1;
break;
}
}
return new int[]{num1, num2};
}
}