//1
int binarySearch(vector<int>& nums, int target) { int left = 0; int right = nums.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) { // 找到目标值,返回索引或其他需要的结果 return mid; } else if (nums[mid] < target) { // 目标值在右半部分 left = mid + 1; } else { // 目标值在左半部分 right = mid - 1; } } // 没有找到目标值 return -1; }
//2
long long repairCars(vector<int>& ranks, int cars) { long long L = 0,R = 1LL*ranks[0]*cars*cars; while(L + 1<R){ long long k = L + (R-L)/2; long long tmp = 0; for(int i = 0;i<ranks.size();i++){ tmp += pow(k/ranks[i],0.5); } if(tmp >= cars) R = k; else if(tmp < cars) L = k; } return R; }
标签:二分,vector,nums,int,cars,long,while,查找 From: https://www.cnblogs.com/fyjie/p/17685357.html