请实现有重复数字的升序数组的二分查找
给定一个 元素有序的(升序)长度为n的整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的第一个出现的target,如果目标值存在返回下标,否则返回 -1
数据范围:
进阶:时间复杂度,空间复杂度
[1,2,4,4,5],4
2
从左到右,查找到第1个为4的,下标为2,返回2
[1,2,4,4,5],3
-1
[1,1,1,1,1],1
0
在普通二分查找基础上,增加一个往左寻找第一个出现的位置即可
int search(int* nums, int numsLen, int target ) { // write code here if(numsLen==0) return -1; int left=0, right=numsLen-1; while(left<=right) { int mid = left+(right-left)/2; if(nums[mid]==target) { while(nums[mid]==target) { mid--; } return mid+1; } if(nums[mid]<target) left=mid+1; if(nums[mid]>target) right=mid-1; } return -1; }
int search(int* nums, int numsLen, int target ) { int zuo=0; int you=numsLen-1; int zhong=0; while(zuo<=you) { zhong=(zuo+you)/2; if(nums[zhong]<target) { zuo=zhong+1; } else if(nums[zhong]>target) { you=zhong-1; } else { int t=zuo; while(nums[t]!=target) { t++; } return t; break; } } return -1; }
nt search(int* nums, int numsLen, int target ) { // write code here int i = 0; int right = numsLen-1; int left = 0; int j = 0; while(left<=right) { i = (right+left)/2; if(nums[i]<target) { left = i+1; } else if(nums[i]>target) { right = i-1; } else { int j = i; while(nums[j-1] == target) { j--; } return j; } } return -1; }
int cond(int* nums, int mid, int target) { return *(nums + mid) >= target; } int binary_search(int* nums, int numsSize, int target, int (*cond) (int*, int, int)) { int l = 0, r = numsSize, m; while (l < r) { m = l + ((r - l) >> 1); if (cond(nums, m, target)) r = m; else l = m + 1; } return l; } int search(int* nums, int numsLen, int target) { int index = binary_search(nums, numsLen, target, cond); if (index == numsLen || *(nums + index) > target) return -1; return index; }