题目:Given an array of integers 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].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
我的解决办法:
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] ret = new int[] { -1, -1 };
int h = nums.length - 1;
int l = 0;
int m;
while (h >= l) {
m = (h + l) / 2;
if (nums[m] > target) {
h = m - 1;
}
if (nums[m] < target) {
l = m + 1;
}
if (nums[m] == target) {
for (int i = l; i <= m; i++) {
if (nums[i] == target) {
ret[0] = i;
break;
}
}
for (int i = m; i <= h; i++) {
if(nums[h]==target){
ret[1]=h;
break;
}
if (nums[i] != target) {
ret[1] = i-1;
break;
}
}
return ret;
}
}
return ret;
}
}
显然没有很好的理解二分查找的概念
二分查找算法是基于有序序列的查找算法,时间复杂度为O(logn)
int[] ret = new int[] { -1, -1 };
if(nums.length==0){
return ret;
}
int h = nums.length - 1;
int l = 0;
if(target<nums[l]||target>nums[h]){
return ret;
}
int m;
while (h >l) {
m=(h+l)/2;
if(nums[m]<target){
l=m+1;
}else{
h=m;
}
}
if(nums[l]!=target){
return ret;
}else{
ret[0]=l;
}
h = nums.length - 1;
l = 0;
while (h > l) {
m=(h+l)/2;
if(nums[m]<=target){
l=m+1;
}else{
h=m;
}
}
if(nums[l]==target){
ret[1]=l;
}else{
ret[1]=l-1;
}
return ret;
在一本书上找到了一个模板
public int solve(int left,int right){
int mid;
while(left<right){//对于[left,right]来说,left==right 意味着找到唯一的的位置
mid =(left+right)/2;
if(条件成立){
right=mid;
}else{
left=mid+1;
}
}
return left;
}
真正大的理解这个,可以画一张图更好的理解