Given a sorted array of integers, 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]
.
public class Solution { public int[] searchRange(int[] nums, int target) { int[] res = new int[2]; int l=0,len=nums.length,r=len-1,mid=0; while(l<=r){ mid=(l+r)>>1; if(nums[mid]==target)break; else if(nums[mid]>target)r=mid-1; else l=mid+1; } if(l<=r){ l=mid-1; while(l>=0 && nums[l]==nums[mid])l--; r=mid+1; while(r<len && nums[r]==nums[mid])r++; res[0]=l+1; res[1]=r-1; }else{ res[0]=-1; res[1]=-1; } return res; } }
int* searchRange(int* nums, int numsSize, int target, int* returnSize) { int* res=(int*)malloc(sizeof(int)*2); int l=0,r=numsSize-1,mid; while(l<=r){ mid=(l+r)>>1; if(nums[mid]==target)break; else if(nums[mid]>target)r=mid-1; else l=mid+1; } if(l<=r){ l=mid-1; while(l>=0 && nums[l]==nums[mid])l--; r=mid+1; while(r<numsSize && nums[r]==nums[mid])r++; res[0]=l+1;res[1]=r-1; *returnSize=2; return res; }else{ res[0]=-1;res[1]=-1; *returnSize=2; return res; } }
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> res; int l=0,len=nums.size(),r=len-1,mid; while(l<=r){ mid=(l+r)>>1; if(nums[mid]==target)break; else if(nums[mid]>target)r=mid-1; else l=mid+1; } if(l<=r){ l=mid-1; while(l>=0 && nums[l]==nums[mid])l--; r=mid+1; while(r<len && nums[r]==nums[mid])r++; res.push_back(l+1); res.push_back(r-1); }else{ res.push_back(-1); res.push_back(-1); } return res; } };
class Solution: # @param {integer[]} nums # @param {integer} target # @return {integer[]} def searchRange(self, nums, target): length=len(nums);l=0;r=length-1;mid=0 res=[-1,-1] while l<=r: mid=(l+r)>>1; if nums[mid]==target:break elif nums[mid]>target:r=mid-1 else:l=mid+1 if l<=r: l=mid-1 while l>=0 and nums[l]==nums[mid]:l-=1 r=mid+1 while r<length and nums[r]==nums[mid]:r+=1 res[0]=l+1;res[1]=r-1 return res
LeetCode 34 Search for a Range (C,C++,Java,Python)
原文地址:http://blog.csdn.net/runningtortoises/article/details/45726387