题解 | #二分查找-II#
二分查找-II
http://www.nowcoder.com/practice/4f470d1d3b734f8aaf2afb014185b395
int search(vector<int>& nums, int target) { int index=nums.size(); int left=0,right=nums.size()-1; while(left<=right) { int mid=(left+right)/2; if(nums[mid]<target) left=mid+1; else { if(nums[mid]==target) index=min(index,mid); right=mid-1; } } if(index==nums.size()) return -1; return index; } };
使用二分法查找,index始终是相等的数中索引最小的