二分查找-I_牛客题霸_牛客网
方法一:遍历找目标值
int search(vector<int>& nums, int target) {// write code herefor(int i = 0; i < nums.size(); i++) {if(target == nums[i]) {return i; // 返回目标值在数组中的索引}}return -1; // 如果找不到目标值,返回-1
}
方法二:二分法查找目标值下标
int search(vector<int>& nums, int target) {// write code hereint len= nums.size();if(len == 0){return -1;}int left = 0,right =len-1;while(left <= right){int mid = (left+right)/2;if(nums[mid]==target){return mid;}else if(nums[mid]<target){left = mid+1;}else if(nums[mid]>target){right = mid-1;}}return -1;
}