704.二分查找 发表于 2023-04-10 分类于 代码随想录 阅读次数: 704. 二分查找123456789101112131415161718192021class Solution {public: int search(vector<int>& nums, int target) { int left=0; int right=nums.size()-1; while(left<=right){ int middle=(left+right)/2; if (nums[middle]>target){ right=middle-1; } else if (nums[middle]<target){ left=middle+1; } else{ return middle; } } return -1; }};1234567891011121314151617181920int search(int* nums, int numsSize, int target){ int left=0; int right=numsSize-1; while(left<=right){ int middle=(left+right)/2; if (nums[middle]>target){ right=middle-1; } else if (nums[middle]<target){ left=middle+1; } else{ return middle; } } return -1; }12345678910111213141516171819202122232425262728293031323334#include<iostream>#include<vector>using namespace std;int main(){ vector <int> nums; int n; cin>>n; int target; cin>>target; while(n--){ int temp; cin>>temp; nums.push_back(temp); } int left=0; int right=nums.size()-1; while(left<=right){ int middle=(left+right)/2; if(nums[middle]>target){ right=middle-1; } else if(nums[middle]<target){ left=middle+1; } else { cout<<middle; break; } } return 0; } -------------本文结束感谢您的阅读-------------老板你好,讨口饭吃打赏微信支付支付宝本文作者: 毛本文链接: http://example.com/2023/04/10/704.二分查找/版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!