LeetCode--034--在排序数组中查找元素的第一个和最后一个位置(java)

给定一个按照升序排列的整数数组 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]
 class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums == null || nums.length == 0)return new int[]{-1,-1};
return new int[]{findFirst(nums,target),findLast(nums,target)};
}
public int findFirst(int[] nums,int target){
int start = 0;
int end = nums.length - 1;
while(start + 1 < end){
int mid = (end - start) / 2 + start;
if(nums[mid] < target){
start = mid;
}else{
end = mid;
}
}
if(nums[start] == target) return start;
if(nums[end] == target) return end;
return -1;
}
public int findLast(int[] nums,int target){
int start = 0;
int end = nums.length - 1;
while(start + 1 < end){
int mid = (end - start) / 2 + start;
if(nums[mid] > target){
end = mid;
}else{
start = mid;
}
}
if(nums[end] == target) return end;
if(nums[start] == target) return start;
return -1;
} }

方法2:(unpassed) 长度小于3会有错误

 class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums == null || nums.length == 0)return new int[]{-1,-1};
if(nums.length == 1 && nums[0] == target) return new int[]{0,0};
int start = 0,end = nums.length -1;
boolean flag = false;
while(start+1<end ){
int mid = (end - start) / 2 + start;
if(nums[mid] < target){
start = mid;
}else if(nums[mid] > target){
end = mid;
}else{
flag = true;
start = mid;
end = mid;
while(start >= 0 && nums[start] == target){
start--;
}
while(end < nums.length && nums[end] == target){
end++;
}
start++;
end--;
break;
}
}
if(flag == true){
return new int[]{start,end};
}
return new int[]{-1,-1};
} }

2019-04-27 19:51:51

上一篇:【C语言用法】C语言的函数“重载”


下一篇:mysql常见查询练习题